我创建了第一个实现套接字服务器的测试应用程序。我有一些问题让客户端接收数据,但服务器获取数据就好了。这是服务器:
ServerSocket socket = new ServerSocket(11111);
System.out.println("CREATING SERVER...");
while (true) {
Socket SERVER_WORK = socket.accept();
BufferedReader clientIN = new BufferedReader(new InputStreamReader(SERVER_WORK.getInputStream()));
PrintWriter outSend = new PrintWriter(SERVER_WORK.getOutputStream());
String ClientSTR = clientIN.readLine();
System.out.println("Client 1: " + ClientSTR);
String toClient = "Hello";
outSend.write(toClient + '\n');
}
这是客户:
System.out.println("CONNECTING TO SERVER...");
while (true) {
Socket clientSocket = new Socket(server, 11111);
BufferedReader fromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
DataOutputStream toServere = new DataOutputStream(clientSocket.getOutputStream());
Scanner in = new Scanner(System.in);
toServere.write(in.nextLine().getBytes());
if (fromServer.ready())
System.out.println(fromServer.readLine());
clientSocket.close();
}
除了接收数据的客户端外,一切正常。
答案 0 :(得分:-1)
我找到了解决方案:我需要一个' \ n'在DataOutputStream / PrintWriter的行的末尾,以使BufferedReader正常工作。