我正在开发一个软件,与套接字,设置与服务器的连接(我安装PgAdmin的数据库)。 我创建客户端e服务器代码,他们完美运行,但我不知道如何通过套接字发送数据,当用户做一些行动。该软件就像一个社交网络,用户可以登录并查看其他用户记录的信息和新闻。客户端服务器多线程套接字
public class LoginForm {
private JTextField EditUsername;
private JTextField EditEmail;
private static Client client;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
client = new Client();
client.connectToServer();
LoginForm window = new LoginForm();
window.Loginframe.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public LoginForm() {
initialize();
}
...
...
String username = "USER"; client.SendToServer(username);
这是我首先将客户端连接到服务器的登录表单。然后当我需要发送信息到服务器时,我不知道我需要做什么!
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
public class Client {
private BufferedReader in;
private PrintWriter out;
private static Socket socket;
private static String number ="0" ;
/**
* Constructs the client by laying out the GUI and registering a
* listener with the textfield so that pressing Enter in the
* listener sends the textfield contents to the server.
*/
public Client() {
}
public void connectToServer() throws IOException {
String host = "localhost";
int port = 4000;
InetAddress address;
try {
address = InetAddress.getByName(host);
socket = new Socket(address, port);
//Send the message to the server
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
String number = "1";
String sendMessage = number;
bw.write(sendMessage);
bw.flush();
System.out.println("Message sent to the server : "+sendMessage);
//Get the return message from the server
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
}
catch (Exception exception)
{
exception.printStackTrace();
}
finally
{
//Closing the socket
try
{
socket.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
public void SendToServer(String username){
}
}
所以这是客户端接收字符串用户,但我需要做什么?创建另一个socket连接? 请帮我,套接字让我发疯。 我必须用户插座(我知道RMI要好得多)
转问这个问题的信息:http://stackoverflow.com/questions/10332799/client-server-client-communication-using-sockets ?rq = 1 –
只需以字符串,对象,字节的形式发送它 - 套接字具有输出流,以便写入它。这就像你会写一些文件。 – Antoniossss
但是当我创建登录表单时,客户端已经在运行?或者我在用户点击按钮时运行它?另外我需要控制用户的访问权限,所以生成的套接字必须为用户创建一个会话 – dvdLucka