socket服务端,多线程,while(true)的胡乱理解

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
连接的步骤是什么? 首先,你需要创建一个ServerSocket对象并指定端口号。然后,在无限循环中,等待客户端连接请求。一旦有连接请求,就创建一个新的Socket对象来处理连接,并将Socket传递给一个新的线程来处理。在线程中,你可以使用Socket对象中的输入和输出流来进行通信。最后,关闭Socket和ServerSocket对象,释放资源。以下是Java代码示例: ``` import java.net.*; import java.io.*; public class MultiThreadedServer implements Runnable { private Socket clientSocket; public static void main(String[] args) throws IOException { ServerSocket serverSocket = null; try { serverSocket = new ServerSocket(8080); System.out.println("Server started."); while (true) { System.out.println("Waiting for a client ..."); Socket socket = serverSocket.accept(); System.out.println("Client accepted"); new Thread(new MultiThreadedServer(socket)).start(); } } catch (IOException e) { e.printStackTrace(); } finally { if (serverSocket != null) { serverSocket.close(); } } } public MultiThreadedServer(Socket socket) { this.clientSocket = socket; } public void run() { try { PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true); BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) { System.out.println("Received message: " + inputLine); out.println(inputLine); } in.close(); out.close(); clientSocket.close(); } catch (IOException e) { e.printStackTrace(); } } } ```
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值