[英]Java: cannot read from socket, thread gets stuck on readLine()
這是我在服務器端的代碼:
@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();
}
如果有人想查看我的整個代碼, 則將其托管在github上
看起來該消息在寫入套接字流后再也不會刷新。
嘗試致電:
toServer.flush();
在println
之后,或者在構造toServer
時啟用自動刷新:
toServer = new PrintWriter(socket.getOutputStream(), true);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.