[英]java sockets client sends to server but fails to listen
我必須做一個非常簡單的TCP服務器,該服務器使用TCP偵聽某些客戶端並以大寫形式返回消息。
連接穩定,客戶端完美地發送了消息,服務器偵聽了消息,但是服務器無法應答,我也不知道為什么會這樣...
服務器:
//imports and stuff you don't really care about
public class ServerThread extends Thread {
private final Socket clientSocket;
private final Main controller;
private final Server server;
BufferedReader in;
PrintWriter out;
//constructor
ServerThread(Socket clientSocket, Main controller, Server server) throws IOException {
this.clientSocket = clientSocket;
this.controller = controller;
this.server = server;
//make input and output streams
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
//THIS MAY BE WRONG
out = new PrintWriter(clientSocket.getOutputStream());
}
@Override
public void run() {
controller.out("Connected: " + clientSocket.getInetAddress().toString());
out.println("test");
try {
String msg;
while ((msg = in.readLine()) != null) {
//Prints this line
System.out.println(clientSocket.getInetAddress().toString() + " says: " + msg);
//THIS MAY BE WRONG
out.println(msg.toUpperCase());
System.out.println("Answered");//this line too
}
}catch(SocketException ex){
destroyMe();
}
catch (IOException ex) {
Logger.getLogger(ServerThread.class.getName()).log(Level.SEVERE, null, ex);
destroyMe();
}
}
//couple of methods that don't interfere here
}
客戶:
public class Client extends Thread {
private final String host = "localhost";
private final int port = 44444;
private final PrintWriter out;
private final Socket socket;
BufferedReader in;
private Main c;
public Client(Main c) throws IOException {
this.c = c;
socket = new Socket(host, port);
out = new PrintWriter(socket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
System.out.println("Connection Opened.");
}
public void send(String str) {
out.println(str); //this works fine
}
@Override
public void run() {
String msg;
while (true) {
try {
//THIS MAY BE WRONG but I don't think so
while ((msg = in.readLine()) != null) {
System.out.println("received: " + msg); //this never happens
c.out(msg);
}
//this line is always reached until I close the connection.
} catch (SocketException ex) {
System.out.println("Connection closed"); //this line is reached too
break;
} catch (IOException ex) {
Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
//This works fine
}
}
}//end of the thread
//there are a couple of methods here but they don't do anything related
}
我沒有發現任何錯誤,但一定有問題。
謝謝你的幫助。
您正在使用PrinterWriter來控制服務器代碼的輸出。
您在創建它時未通過out = new PrintWriter(clientSocket.getOutputStream());
打開自動刷新功能out = new PrintWriter(clientSocket.getOutputStream());
當您通過println,printf或format方法編寫消息時,將按照文檔打開自動刷新功能。
打開自動刷新並使用上述方法為您編寫消息,在要發送消息時調用flush方法,或者完全使用其他方法來控制Server輸出流。
http://docs.oracle.com/javase/7/docs/api/java/io/PrintWriter.html
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.