java socket一对多通信如何实现?

2024-12-04 16:46:51
推荐回答(2个)
回答1:

【server端】

import java.io.*;
import java.net.*;
public class MultiSocketServer
{
public static void main(String str[]) throws IOException
{
ServerSocket server=new ServerSocket(3333);//绑定端口
while(true)
{
Socket client=server.accept();//监听
ChildTh child=new ChildTh(client);
Thread t=new Thread(child);
t.start();
}
}
}
class ChildTh implements Runnable
{
private Socket client;
public ChildTh(Socket client)
{
this.client=client;
}

public void run() {
try
{
BufferedReader in=new BufferedReader(new InputStreamReader(client.getInputStream()));
PrintWriter out=new PrintWriter(client.getOutputStream());
while(true)
{
String s=in.readLine();
System.out.println(s);
out.println("has received……");
out.flush();
if(s.equals("end"))
break;
}
client.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
【client端】
import java.net.*;
import java.io.*;
public class MultiSocketClient
{
static Socket server;
public static void main(String str[]) throws IOException
{
server=new Socket("222.195.151.47",3333);
BufferedReader in=new BufferedReader(new InputStreamReader(server.getInputStream()));
PrintWriter out=new PrintWriter(server.getOutputStream());
BufferedReader wt=new BufferedReader(new InputStreamReader(System.in));
while(true)
{
String s=wt.readLine();
out.println(s);
out.flush();
if(s.equals("end"))
{
break;
}
System.out.println(in.readLine());
}
server.close();
}
}

回答2:

服务器端发送消息,你要知道给哪个客户端发,应该是将所有的客户端连接都放在数组里,然后遍历数组发送
参考下吧: http://wenku.baidu.com/view/a9598469c5da50e2524d7f82.html