Java 通过服务器将更改从一个客户端推送到所有其他连接的客户端?
所以我有一个客户:Java 通过服务器将更改从一个客户端推送到所有其他连接的客户端?,java,sockets,network-programming,Java,Sockets,Network Programming,所以我有一个客户: public class TalkClient extends Thread { private int port; private String host; DocCntl theDocCntl; public TalkClient(String host, int port) throws IOException { this.host = host; this.port = port; theDocCntl = new
public class TalkClient extends Thread
{
private int port;
private String host;
DocCntl theDocCntl;
public TalkClient(String host, int port) throws IOException
{
this.host = host;
this.port = port;
theDocCntl = new DocCntl(this);
}
public void run()
{
try
{
System.out.println("Seeking connection...");
Socket socket = new Socket(host, port);
DataInputStream in = new DataInputStream(socket.getInputStream());
BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
}catch(IOException e)
{
e.printStackTrace();
}
}
public static void main(String [] args)
{
int port = 5050;
try
{
Thread t = new TalkClient("127.0.0.1", port);
t.start();
}catch(IOException e)
{
e.printStackTrace();
}
}
public void pushToServer(){
String theData = this.theDocCntl.theDoc.docTA.getText();
}
}
我有一个服务器:
public class TalkServer extends Thread
{
private ServerSocket serverSocket;
public static DocCntl theCntl;
public TalkServer(int port) throws IOException
{
serverSocket = new ServerSocket(port);
}
public void run()
{
try
{
System.out.println("Listening for connections...");
Socket client = serverSocket.accept();
DataInputStream in = new DataInputStream(client.getInputStream());
BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
DataOutputStream out = new DataOutputStream(client.getOutputStream());
}catch(IOException e)
{
e.printStackTrace();
}
}
public static void main(String [] args)
{
int port = 5050;
try
{
Thread t = new TalkServer(port);
t.start();
}catch(IOException e)
{
e.printStackTrace();
}
}
}
在客户机中,我有一个名为pushToServer的方法,我希望从客户机上的textArea获取字符串数据,然后将其推送到所有其他连接的客户机。但我不知道如何处理通过套接字将消息发送到每个单独连接的客户端。我已经考虑过了,我想我需要做三件事:
1) 创建并维护已连接客户端(线程)的列表。在服务器类本身中?还是在别的班
2) 在服务器上,使用某种方法从一个客户端“捕获”字符串数据,然后将其推送到所有其他客户端。这就是为什么(我认为)我需要客户名单。如果我能弄清楚如何捕捉这个(可能是通过输入流?),然后通过客户列表迭代到他们的文本区域
3) 在客户端,我需要能够从服务器捕获字符串
在这三件事上的任何帮助都将不胜感激 从我在代码中读到的内容来看,我可以说您的程序是针对1客户端/1服务器的。您没有while(true)循环来接受新的传入连接请参见