如何通过Java套接字正确设置服务器部分?

时间:2016-03-12 19:42:24

标签: java sockets server client

我已编写服务器和客户端部分,请参阅代码:

//this I run on my firt PC
public class TCPServer {

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

    TCPServer server = new TCPServer();
    server.run();
 }

 public void run() throws Exception{
    ServerSocket socket = new ServerSocket(6789);
    Socket SOCK = socket.accept();
    BufferedReader BR = new BufferedReader(new InputStreamReader(SOCK.getInputStream()));

    String msg = BR.readLine();
    System.out.println(msg);

    if(msg != null){
        PrintStream PS = new PrintStream(SOCK.getOutputStream());
        PS.print("MESSAGE RECEIVED");
    }
 }
}


//This I run on my notebook
public class TCPClient {

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

            TCPClient client = new TCPClient();
            client.run();
        }

        public void run() throws Exception{
            Socket clientSocket = new Socket("192.168.88.77",6789);
            PrintStream PS = new  PrintStream(clientSocket.getOutputStream());
            PS.print("Hello from GLADIS VLADLEN");

            BufferedReader BR = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));

            String msg = BR.readLine();
            System.out.println(msg);

        }
}

运行此应用程序后没有任何反应。只有在我停止客户端app消息后才被服务器部分接收。为什么会这样?我试图关闭防火墙,但这对我没有帮助。

1 个答案:

答案 0 :(得分:1)

服务器和客户端都使用BufferedReader#readLine()读取一行。但是PrintStream正在发送没有行终止符的字符。

尝试拨打println而不是print