我试图让一个小的java应用程序进行聊天 . 我想要的是ServerSocket到 accept one and only one connection . 如果第二个Socket尝试连接到ServerSocket,它将抛出异常,因此启动套接字的用户知道他可以't connect to that ServerSocket I looked at the javadoc and I'找到该构造函数 .
public ServerSocket(int port, int backlog) throws IOException
创建服务器套接字并使用指定的待办事项将其绑定到指定的本地端口号 . 端口号为0表示通常从临时端口范围自动分配端口号 . 然后可以通过调用getLocalPort来检索此端口号 .
我试过这个
class Service implements Runnable {
private Socket maChaussette;
Service(Socket s) {
maChaussette = s;
}
public void run() {
System.out.println("connection established");
while (true) {
System.out.print("");
}
//maChaussette.close();
}
}
Server :
class Serv {
public static void main(String[] a) throws IOException {
ServerSocket socketAttente;
socketAttente = new ServerSocket(11111, 1);
boolean conn = false;
Thread t;
while (true) {
Socket s = socketAttente.accept();
t = new Thread(new Service(s));
t.start();
}
//socketAttente.close();
}
}
client
public class Cll {
public static final int PORT = 11111;
public static void main(String[] arguments) {
try {
Socket service = new Socket("localhost", PORT);
while (true) {
System.out.print("");
}
} catch (Exception e) {
System.err.println("Error");
e.printStackTrace();
System.exit(1);
}
}
}
我不尝试沟通或其他什么,我只是让这些类试图阻止与ServerSocket的连接数 .
但是如果我运行两个Cll程序,我会得到两次“连接已 Build ”的消息 .
有人知道如何限制ServerSocket上的连接吗?
1 回答
只需在接受一个连接后关闭ServerSocket即可 . 并摆脱了接受循环周围的'while(true)' .