本文介绍了Java套接字服务器 - >只接受一个请求,然后停止接受?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想为我的一个项目编写一个简单的套接字服务器,但它只接受一个请求,然后从任何地方不接受任何其他东西。
I'm trying to write a simple socket server for a project of mine, but it only accepts one request and then doesn't accept anything else from anywhere.
public void run() {
println("Socket server running...");
try {
sock = new ServerSocket(20424);
while(true) {
clientSocket = sock.accept();
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String data;
while((data = in.readLine()) != null) {
println("[SocketServer] " + data);
if(data.equalsIgnoreCase("COUNT(TRIGGERS)")) {
out.println(getTriggerCount());
}
}
out.println("endOfStream");
out.close();
in.close();
clientSocket.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
它会接受一个请求,的数据,但之后没有什么工作。这是我用来连接的客户端:
It will accept one request and respond with the correct amount of data, but after that nothing works. Here's the client I'm using to connect:
public static void main(String[] args) {
try {
socket = new Socket("localhost", 20424);
out = new PrintWriter(socket.getOutputStream(),
true);
in = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
out.println("COUNT(TRIGGERS)");
String data;
while((data = in.readLine()) != null) {
System.out.println(data);
}
socket.close();
} catch (UnknownHostException e) {
System.out.println("Unknown host");
System.exit(1);
} catch (IOException e) {
System.out.println("No I/O");
System.exit(1);
}
}
推荐答案
将在内部结束时立即接受下一个连接...
It will accept the next connection as soon as the inner while ends...
也许你想用自己的线程为传入连接创建套接字处理程序,多重连接。
Maybe you want to create socket handlers for the incoming connections with their own threads, so you can handle multiple connections simulatanously.
这篇关于Java套接字服务器 - >只接受一个请求,然后停止接受?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!