public void createServer(int port, ServerMsgPanel serverMsgPanel) throws IOException { long clientAccessNumber = 1L; this.serverMsgPanel = serverMsgPanel; try { this.serverSocket = new ServerSocket(port); serverMsgPanel.msgTextArea.setText("服务器启动于:" + InetAddress.getLocalHost() + ":" + this.serverSocket.getLocalPort() + "\n"); while(true) { Socket clientSocket = this.serverSocket.accept(); serverMsgPanel.msgTextArea.append("已连接用户:" + clientSocket + "\n"); DataOutputStream outputData = new DataOutputStream(clientSocket.getOutputStream()); this.clientDataHash.put(clientSocket, outputData); this.clientNameHash.put(clientSocket, "新玩家" + clientAccessNumber++); ServerThread serverThread = new ServerThread(clientSocket, this.clientDataHash, this.clientNameHash, this.chessPeerHash, serverMsgPanel); serverThread.start(); } } catch (IOException var8) { var8.printStackTrace(); } }
时间: 2024-03-30 11:34:00 浏览: 42
创建一个Server服务
这段代码是用Java语言编写的创建服务器的方法。它打开一个ServerSocket,监听指定的端口,等待客户端连接。当有客户端连接时,会创建一个Socket对象,将客户端的输出流包装成DataOutputStream对象,并将客户端的Socket、DataOutputStream和客户端名称等信息存储在哈希表中。然后,启动一个ServerThread线程来处理与该客户端的通信。这个方法还接受一个ServerMsgPanel参数,用于在GUI界面上显示服务器的日志信息。
阅读全文