50,731
社区成员
发帖
与我相关
我的任务
分享
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketAddress;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.List;
public class Server {
private List<SocketAddress> all = new ArrayList<SocketAddress>();
public static void main(String args) throws IOException {
new Server().start();
}
public void start() {
try {
DatagramSocket server = new DatagramSocket(30003);
while(true) {
MyChannel channel = new MyChannel(server);
new Thread(channel).start();
}
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private class MyChannel implements Runnable{
private DatagramSocket server;
private DatagramPacket packet;
public MyChannel(DatagramSocket server) {
this.server = server;
try {
byte container = new byte;
packet =new DatagramPacket(container,container.length);
server.receive(packet);
SocketAddress address = packet.getSocketAddress();
all.add(address); //加入到容器
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private String receive() {
String msg;
msg = new String(packet.getData(),0,packet.getLength());
return msg;
}
@Override
public void run() {
// TODO Auto-generated method stub
System.out.println(receive());
sendOthers(packet);
}
private void sendOthers(DatagramPacket dp) {
//String msg = receive();
//遍历容器
for(SocketAddress sa:all) {
try {
String str = new String(dp.getData(),0,dp.getLength());
DatagramPacket dd = new DatagramPacket(str.getBytes(),str.getBytes().length,sa);
server.send(dd);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}