我有多个客户端将数据发送到相同的预定义IP地址和端口号。我正在尝试 java socket 。我有一个消费者代码(服务器)接受来自多个客户端的数据。但我的消费者代码只收听第一个客户数据。它忽略了第二个。
服务器: -
public class consumer {
public static void main(String[] args) throws IOException {
ServerSocket serverScoket=new ServerSocket(3333,10);
Socket socket=serverScoket.accept();
DataInputStream din=new DataInputStream(socket.getInputStream());
while(true){
String str="";
str=din.readUTF();
if(str.length()>0)
System.out.println("client says: "+str);
}
}
}
第一位客户: -
public class uploader1 {
public static void main(String[] args) throws UnknownHostException, IOException, InterruptedException {
// TODO Auto-generated method stub
Socket s=new Socket("localhost",3333);
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
int i = 0;
while(i++<15){
Thread.sleep(1000);
dout.writeUTF("u1 "+i);
dout.flush();
}
dout.close();
s.close();
}
}
第二位客户: -
public class uploader2 {
public static void main(String[] args) throws UnknownHostException, IOException, InterruptedException {
// TODO Auto-generated method stub
Socket s=new Socket("localhost",3333);
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
int i = 0;
while(i++<15){
Thread.sleep(1000);
dout.writeUTF("u2 "+i);
dout.flush();
}
dout.close();
s.close();
}
}
如果执行序列是consumer,uploader1,uploader2,那么它就像这样打印
client says: u1 1
client says: u1 2
client says: u1 3
client says: u1 4
client says: u1 5
client says: u1 6
client says: u1 7
client says: u1 8
client says: u1 9
client says: u1 10
client says: u1 11
client says: u1 12
client says: u1 13
client says: u1 14
client says: u1 15
我是否可以通过Java套接字编程实现它,或者我需要找到其他方法。请建议。