我正在尝试编写我的第一个 socket 服务器,所以我决定从非常简单的事情开始,只是为了弄清楚流程 :) 我正在编写一个简单的 Java 回显服务器,但问题是(因为某种原因?!)我在客户端没有收到服务器响应,尽管请求已经在服务器中接收到。
package poc.client;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
public class Client {
public static void main(String[] args) {
try {
final Socket socket = new Socket((String) null, 50000);
final BufferedReader reader = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
final PrintWriter writer = new PrintWriter(
socket.getOutputStream(), true);
writer.println("ala bala\r\n");
writer.flush();
writer.close();
System.out.println(reader.readLine());
System.out.flush();
} catch (Exception ex) {
Logger.getAnonymouseLogger().throwing(TAG, "main", ex);
}
}
}
服务器部分是:
package poc.server;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
/**
* debugging purposes only
*/
@SuppressWarnings("unused")
private static final String TAG = Server.class.getSimpleName();
public static void main(String[] args) {
try {
final ServerSocket socket = new ServerSocket(50000);
while (true) {
final Socket clientSocket = socket.accept();
final BufferedReader reader = new BufferedReader(
new InputStreamReader(clientSocket.getInputStream()));
final PrintWriter writer = new PrintWriter(clientSocket
.getOutputStream(), true);
writer.println(reader.readLine());
writer.flush();
writer.close();
}
} catch (IOException e) {
Logger.getAnonymouseLogger().throwins(TAG, "main",ex);
}
}
}
我阅读了所有Oracle基础套接字教程等,但我就是无法弄清楚问题所在 - 我成功地向服务器套接字写入数据,但似乎无法获取响应。