简体   繁体   English

客户端不向服务器发送数据

[英]Client does not send data to server

I am having problem even with this very basic client-server application. 即使使用此非常基本的客户端服务器应用程序,我也遇到问题。 The client is not sending data/ the server is not receiving. 客户端未发送数据/服务器未接收。 I cannot understand where is the problem. 我不明白问题出在哪里。 I am even starting to think that i did not understand anything about sockets. 我什至开始认为我对套接字一无所知。

This is the Server code: 这是服务器代码:

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");
    }
}
}

This is the client code: 这是客户端代码:

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");
    }

}
}

If I run both on the same machine, the server prints correctly "client connected .....", but then prints no more. 如果我都在同一台计算机上运行,​​则服务器正确打印“客户端已连接.....”,但随后不再打印。

What is the problem? 问题是什么?

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. 因此,服务器可能无法知道该行应该结束,并阻塞直到在流中找到EOL为止。 Or until the client closes its socket. 或直到客户端关闭其套接字。

In client code, you decorate your output stream with PrintWriter , so you can use println . 在客户端代码中,您可以使用PrintWriter装饰输出流,以便可以使用println Replace 更换

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

by: 通过:

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

Flush is useless since have request autoflush (true in PrintWriter constructor). 冲洗是没有用的,因为有请求自动冲洗(在PrintWriter构造函数中为true)。

In server code, you can use a BuffererdReader decorator instead of Scanner: 在服务器代码中,可以使用BuffererdReader装饰器代替Scanner:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM