我正在尝试编写我的第一个套接字服务器,所以我决定从一些非常简单的东西开始,只是为了弄清楚流程:) 我正在编写一个简单的 java echo 服务器,但问题是(出于某种原因?! )我没有在客户端收到服务器响应,尽管请求是在服务器中收到的。
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 基本套接字教程/等,但我不知道出了什么问题 - 我已成功写入服务器套接字,但我似乎无法获得响应。