我是客户端/服务器编程的新手,所以我试着写一个简单的点对点聊天程序,这样每个程序都有自己的客户端和服务器,程序直接连接就像这样。
Program1 Program2
|----------| |----------|
|--Client--|-------------->|--Server--|
|----------| connections |----------|
|--Server--|<--------------|--Client--|
|----------| |----------|
问题是服务器和客户端已连接,但消息根本无法到达服务器。
我用调试器逐行跟踪代码,并注意到在服务器的(正确)初始化之后,当它到达第二个writer.readLine()
时,调试器只是停止跟踪代码,就像线程正在等待要发生的事情和应该获取和打印消息的循环根本不运行。
服务器:
@Override
public void run() {
try {
// the following code is executed
server = new ServerSocket(port);
port = server.getLocalPort();
logMessage("[Server]Server started.");
logMessage("[Server]Server is waiting on port: " + this.port + ".");
while(true) {
logMessage("[Server]Waiting for connection...");
client = server.accept();
logMessage("[Server]Client connecting on port: " + port + ".");
logMessage("[Server]Client ip: " + client.getInetAddress());
requestConnection(); // Here I ask the user if he want to accept the client or disconnect
try {
synchronized(this) {
this.wait(); // Waiting for the user responce...
}
} catch (InterruptedException e) {
e.printStackTrace();
}
// When the user write the answer the thread wake up!
PrintWriter writer = new PrintWriter(new OutputStreamWriter(client.getOutputStream()));
if(!connectionAccepted.toUpperCase().equals("Y")) {
writer.println(Connection.REFUSED.ordinal());
writer.flush();
writer.close();
client.close();
System.out.println("Connection refused.");
continue;
}
writer.println(Connection.ACCEPTED.ordinal());
writer.flush();
System.out.println("Connection accepted.");
BufferedReader reader = new BufferedReader(new InputStreamReader(client.getInputStream()));
message = reader.readLine(); // This code get the port where the client of this program has to connect to
GUI.connect(client.getInetAddress().getHostName(), Integer.parseInt(message));
message = reader.readLine(); // Here is where the debug stop
while(!message.equals("/disconnect")) {
if(message != null)
logMessage(message);
message = reader.readLine();
System.out.println("Waiting for message..."); // This method should be called several times but in the console there is no message
}
client.close();
}
} catch (IOException e) {
logStackTrace(e);
}
}
客户端:
@Override
public void run() {
try {
client = new Socket(host, port);
BufferedReader reader = new BufferedReader(new InputStreamReader(client.getInputStream()));
String message = reader.readLine();
logMessage("[Client]Message recieved: " + message);
try {
if(Integer.parseInt(message) == Connection.ACCEPTED.ordinal()) {
logMessage("[Client]Connection accepted.");
} else {
logMessage("[Client]Connection refused.");
}
} catch(NumberFormatException e) {
logStackTrace(e);
reader.close();
}
writer = new PrintWriter(new OutputStreamWriter(client.getOutputStream()));
writer.println(GUI.getServer().getPort());
writer.flush();
} catch (IOException e) {
logStackTrace(e);
}
}
客户端的“发送”方法:
public void send(String message) {
writer.println(message);
writer.flush();
}