客户端不会将数据发送到服务器

时间:2017-12-17 12:13:31

标签: java sockets networking

即使使用这个非常基本的客户端 - 服务器应用程序,我也遇到了问题。客户端没有发送数据/服务器没有收到。我无法理解问题出在哪里。我甚至开始认为我对套接字一无所知。

这是服务器代码:

public class Server
{
public static void main(String args[])
{
    try{
        ServerSocket serverSocket = new ServerSocket(3000);

        Socket socket = serverSocket.accept();

        System.out.println("Client connected: "+socket.getInetAddress.toString());

        Scanner scanner = new Scanner(socket.getInputStream());

        while(true)
        {
            System.out.println(scanner.nextLine());
        }
    }catch(IOException e)
    {
        System.out.println("error");
    }
}
}

这是客户端代码:

public class Client
{
public static void main(String args[])
{
    Socket socket;
    PrintWriter printWriter;


    try {
        socket = new Socket("127.0.0.1", 3000);
        printWriter = new PrintWriter(socket.getOutputStream(), true);

        while(true)
        {
            printWriter.write("frejwnnnnnnnnnnnnnnnnnnnnnnnnosfmxdawehtcielwhctowhg,vort,hyvorjtv,h");
            printWriter.flush();
        }

    }catch(IOException e)
    {
        System.out.print("error\n");
    }

}
}

如果我在同一台机器上同时运行,则服务器正确打印"客户端连接.....",但随后不再打印。

有什么问题?

2 个答案:

答案 0 :(得分:1)

The server reads the next line. The client doesn't send any line ending. So the server can't possibly know that the line is supposed to be ended, and blocks until it finds an EOL in the stream. Or until the client closes its socket.

答案 1 :(得分:0)

在客户端代码中,您使用PrintWriter修饰输出流,因此您可以使用println。 取代

printWriter.write("frejwnnnnn...rjtv,h");
printWriter.flush();

由:

printWriter.println("frejwnnnnn...rjtv,h");

由于请求autoflush(在PrintWriter构造函数中为true),因此刷新是无用的。

在服务器代码中,您可以使用BuffererdReader装饰器而不是Scanner:

BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String inputLine;
while ((inputLine = br.readLine()) != null) {
    System.out.println(inputLine);
}