英文:
Prevent server terminating in client (golang) server (Java) application
问题
我有一个简单的Java回显服务器:
int portNumber = 4444;
try (
ServerSocket serverSocket =
new ServerSocket(Integer.parseInt(args[0]));
Socket clientSocket = serverSocket.accept();
PrintWriter out =
new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(
new InputStreamReader(clientSocket.getInputStream()));
) {
String inputLine;
while ((inputLine = in.readLine()) != null) {
out.println(inputLine);
System.out.println(inputLine);
}
} catch (IOException e) {
System.out.println("Exception caught when trying to listen on port "
+ portNumber + " or listening for a connection");
System.out.println(e.getMessage());
}
还有一个简单的Go语言客户端:
func main() {
fmt.Println("start client")
conn, err := net.Dial("tcp", "localhost:4444")
if err != nil {
log.Fatal("Connection error", err)
}
conn.Write([]byte("hello world"))
conn.Close()
fmt.Println("done")
}
当我启动服务器然后运行客户端时,服务器按预期回显“hello world”,但然后服务器退出/终止。
问题:如何防止Java服务器终止并强制服务器持续等待更多客户端请求?
英文:
I have a simple echo-server in Java:
int portNumber = 4444;
try (
ServerSocket serverSocket =
new ServerSocket(Integer.parseInt(args[0]));
Socket clientSocket = serverSocket.accept();
PrintWriter out =
new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(
new InputStreamReader(clientSocket.getInputStream()));
) {
String inputLine;
while ((inputLine = in.readLine()) != null) {
out.println(inputLine);
System.out.println(inputLine);
}
} catch (IOException e) {
System.out.println("Exception caught when trying to listen on port "
+ portNumber + " or listening for a connection");
System.out.println(e.getMessage());
}
and a simple golang client:
func main() {
fmt.Println("start client")
conn, err := net.Dial("tcp", "localhost:4444")
if err != nil {
log.Fatal("Connection error", err)
}
conn.Write([]byte("hello world"))
conn.Close()
fmt.Println("done")
}
When I start the server and then run the client, the server echo's "hello world" as expected but then the server exits/terminates.
Q. How do I prevent this Java termination and force the server to continually wait for more client requests?
答案1
得分: 0
当客户端终止时,服务器端的readLine
将导致流的结束。因此,如果您希望服务器持续监听新连接,只需将上述服务器代码放在一个无限循环中即可。
例如:
while (true) {
// 上述代码
}
对于Play应用程序来说,这就足够了。
英文:
When the client terminates, the readLine
on server side will result in the end of the stream. So if you want the server to continuously listen for new connections the simply put the above server code in a endless loop.
e.g.
while (true) {
// above code
}
For a play application that would be adequate.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论