gpt4 book ai didi

Java:无法从套接字读取,线程卡在 readLine() 上

转载 作者:太空宇宙 更新时间:2023-11-04 10:26:04 25 4
gpt4 key购买 nike

这是我的服务器端代码:

@Override
public void run(){
String message;
String command;
String[] arguments;

try{
BufferedReader inStream = new BufferedReader(
new InputStreamReader(
clientSocket.getInputStream()));

while(online){
message = inStream.readLine();

if(message == null)
continue;

if(message.charAt(0) == '/'){
int endOfCommandIndex = message.indexOf(' ');
command = message.substring(1, endOfCommandIndex);
arguments = message.substring(endOfCommandIndex + 1).split(" ");

if(command.equals("login")){
setUserName(arguments[0]);
setName(arguments[0]);

sendMessage(this, "Connected");
}
//....
}
}
}

正如标题中提到的,线程从 Socket 的 InputStream 读取数据时卡住了(我检查了 JDB,这不是条件等待,因为它似乎仍在“运行”)。

我尝试向套接字写入一行,但它根本没有改变其状态。我正在尝试构建一个类似聊天的本地应用程序,并且我对套接字和流非常陌生。提前致谢。

对于客户端:

String msg;
try{
while(!((msg = stdIn.readLine()).equals("/quit")))
toServer.println(msg);
}
catch(IOException e){
e.printStackTrace();
}

如果有人想查看我的整个代码,it is here hosted on github

最佳答案

看起来消息在写入套接字流后从未刷新。

尝试任一调用:

toServer.flush();

println之后,或者在构造toServer时启用自动刷新:

toServer = new PrintWriter(socket.getOutputStream(), true);

关于Java:无法从套接字读取,线程卡在 readLine() 上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50514098/

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