我必须做一个非常简单的TCP服务器,它使用TCP监听某个客户端并以大写形式返回消息。java套接字客户端发送到服务器,但无法听
连接stablishes精致,完美的客户发送消息和服务器监听到他们,但服务器将不回答,我没有的为什么会这样一个线索...
服务器:
//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
}
我看不出有什么错,但一定有东西。
感谢您的帮助。
你可能想看看这个:http://stackoverflow.com/questions/2165006/simple-java-client-server-program –
谢谢,实际上是想等流选项是逻辑的事情做...我想我太混乱了。 –