gpt4 book ai didi

java - java SocketServer 是如何工作的?

转载 作者:行者123 更新时间:2023-12-02 02:38:21 24 4
gpt4 key购买 nike

我是java新手,我无法理解void go()方法的while循环部分。accept()方法等待客户端请求连接到服务器,那么为什么像Print writer等其他语句,没有被执行?

其他语句是否在 while 循环中等待accept()方法运行?

 import java.io.*;
import java.net.*;
import java.util.*;


public class VerySimpleChatServer
{
ArrayList clientOutputStreams;

public class ClientHandler implements Runnable {
BufferedReader reader;
Socket sock;

public ClientHandler(Socket clientSOcket) {
try {
sock = clientSOcket;
InputStreamReader isReader = new InputStreamReader(sock.getInputStream());
reader = new BufferedReader(isReader);

} catch (Exception ex) { ex.printStackTrace(); }
}

public void run() {
String message;
try {
while ((message = reader.readLine()) != null) {
System.out.println("read " + message);
tellEveryone(message);
}
} catch (Exception ex) { ex.printStackTrace(); }
}
}

public static void main(String[] args) {
new VerySimpleChatServer().go();
}

public void go() {
clientOutputStreams = new ArrayList();
try {
ServerSocket serverSock = new ServerSocket(5000);
while(true) {
Socket clientSocket = serverSock.accept();
PrintWriter writer = new PrintWriter(clientSocket.getOutputStream());
clientOutputStreams.add(writer);

Thread t = new Thread(new ClientHandler(clientSocket));
t.start();
System.out.println("got a connection");
}
} catch (Exception ex) { ex.printStackTrace(); }
}

public void tellEveryone(String message) {
Iterator it = clientOutputStreams.iterator();
while (it.hasNext()) {
try {
PrintWriter writer = (PrintWriter) it.next();
writer.println(message);
writer.flush();
} catch (Exception ex) { ex.printStackTrace(); }
}
}
}

没有任何线索,请帮忙

最佳答案

该接受方法不仅仅等待

阻止。仅当该方法返回时才会继续执行! “执行流程”就此停止 - 在该方法调用返回之前,以下语句无关紧要。

这就是全部内容了。

关于java - java SocketServer 是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45892720/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com