我完成了一个客户端/服务器套接字通信程序,它运行良好。现在我正在尝试弄清楚如何使服务器同时拥有多个客户端连接。我已经查看了一些资料,发现有不止一种方法可以实现这个功能。因此,我来这里寻求帮助和建议。
我的服务器:
我的服务器:
public class Server {
private ServerSocket serverSocket = null;
private Socket clientSocket = null;
public Server() {
try {
serverSocket = new ServerSocket(7003);
} catch (IOException e) {
System.err.println("Could not listen on port: 7003");
System.exit(1);
}
try {
clientSocket = serverSocket.accept();
} catch (IOException e) {
System.err.println("Accept failed");
System.exit(1);
}
}
public void startServer() throws IOException {
PrintWriter output = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader input = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String inputLine, outputLine;
outputLine = "Connected to Server";
output.println(outputLine);
while ((inputLine = input.readLine()) != null) {
// This just determines users input and server ruturns output based on that
outputLine = this.getServerOutput(inputLine);
output.println(outputLine);
if (outputLine.equals("Bye"))
break;
}
output.close();
input.close();
clientSocket.close();
serverSocket.close();
}
}
我需要在构造函数中创建线程并启动 startServer()
还是在运行方法中实现?
shutdownNow()
不会杀死服务器,因为accept()忽略了中断。在这里关闭服务器套接字是正确的方法。startServer()
应该真正成为runServer()
,因为它永远不会返回。拥有启动和停止方法是具有误导性的。如果从未使用,则为什么要提交一个Callable
?socket.close()
应该在try/finally块内。服务器接受循环也是如此。 - Gray