简体   繁体   中英

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. Or until the client closes its socket.

In client code, you decorate your output stream with PrintWriter , so you can use 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).

In server code, you can use a BuffererdReader decorator instead of Scanner:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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