这很容易!我制作了这个程序(服务器端):
import java.net.ServerSocket;
import java.net.Socket;
import java.io.DataInputStream;
import java.io.DataOutputStream;
public class Host{
public static void main(String[] args) throws Exception{
while(true){
ServerSocket ss = new ServerSocket(1300);
Socket s = ss.accept();
DataInputStream din = new DataInputStream(s.getInputStream());
String msgin = din.readUTF();
System.out.println(msgin);
ss.close();
s.close();
din.close();
}
}
}
客户端:
import java.net.Socket;
import java.io.DataInputStream;
import java.io.DataOutputStream;
public class Client{
public static void main(String[] args) throws Exception{
while(true){
Socket s = new Socket("localhost", 1300);
DataOutputStream dout = new DataOutputStream(s.getOutputStream());
dout.writeUTF("hello");
s.close();
dout.close();
}
}
}
它可以工作,因为您可以使用相同的 ServerSocket 声明大量的 Socket,因此例如这也可以:
ServerSocket ss = new ServerSocket(1300);
Socket a = ss.accept();
Socket b = ss.accept();
Socket c = ss.accept();
你有 3 个套接字......记住:当你声明一个套接字时,java 等待客户端连接!代码:
客户:
import java.net.Socket;
public class client {
public static void main(String[] args) throws Exception{
Socket a = new Socket("localhost", 1300);
Thread.sleep(3000);
Socket b = new Socket("localhost", 1300);
Thread.sleep(3000);
Socket c = new Socket("localhost", 1300);
Thread.sleep(3000);
a.close();
b.close();
c.close();
}
}
服务器:
import java.net.ServerSocket;
import java.net.Socket;
public class server {
public static void main(String[] args) throws Exception{
ServerSocket ss = new ServerSocket(1300);
System.err.println("Listening...");
Socket a = ss.accept();
System.err.println("1");
Socket b = ss.accept();
System.err.println("2");
Socket c = ss.accept();
System.err.println("3");
}
}