客户端-服务器,TCPsocket

Client-server, TCPsocket

这是客户端的代码:

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;



public class Client_TCP {

public static void main(String[] args) throws IOException {

    Socket client_socket = new Socket("127.0.0.1", 1025);

    DataOutputStream os = new DataOutputStream(client_socket.getOutputStream());
    os.writeBytes("Hi Server, I'm the Client. How are you?");

    BufferedReader br = new BufferedReader(new InputStreamReader(client_socket.getInputStream()));

    String line = new String("");
    String supportLine=new String("");

    while((line=br.readLine()) != null)
    supportLine = line;

    System.out.println(supportLine);

    os.close();
    br.close();
    client_socket.close();

    }

}

上面是我们连接客户端的服务器代码:

import java.io.BufferedReader;  
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;



    public class ServerTCP {

        public static void main(String[] args) throws IOException {

        ServerSocket server_Socket = new ServerSocket();
        server_Socket.bind(new InetSocketAddress(1025));

        Socket welcomeSocket = server_Socket.accept();
        System.out.println("Connection done on: " + welcomeSocket.getPort());

        BufferedReader br = new BufferedReader(new InputStreamReader(welcomeSocket.getInputStream()));

        String line= new String("");
        String supportLine = new String("");

        while((line=br.readLine()) != null ) {

            supportLine=supportLine + line; 
        }

        System.out.println(supportLine);

        DataOutputStream os = new DataOutputStream(welcomeSocket.getOutputStream());
        os.writeBytes("I'm fine thanks! And you?");

        br.close();
        os.close();
        welcomeSocket.close();          
    }

}

如您所见,客户端发送消息:"Hi Server, I'm the Client. How are you?" 服务器收到消息并重播:"I'm fine thanks! And you?"。 客户端的消息正确地到达服务器。但是,服务器的消息反而没有到达客户端。

我需要你的帮助来解决这个问题。你能帮帮我吗?

谢谢,再见

首先,如果您希望立即read/write,您应该在发送数据后刷新 OutputStream:

os.flush();

其次,BufferedReader

见API

Reads a line of text. A line is considered to be terminated by any one of a line feed ('\n'), a carriage return ('\r'), or a carriage return followed immediately by a linefeed.

由于您的客户端(和服务器)没有发送行尾字符,服务器(和客户端)可能会阻止尝试读取该行。如果服务器(and/or 客户端)需要它,则在发送数据时包括它。