I tried building a TCP server and client using Java. They can connect, they work well, but I have a single error.
This is the server side:
package com.company;
import java.io.*;
import java.net.*;
public class Main {
public static void main (String[] args) throws IOException {
System.out.println("The server is ready");
ServerSocket serverSocket = new ServerSocket (1234);
Socket clientSocket = serverSocket.accept ();
BufferedReader in = new BufferedReader (new InputStreamReader (clientSocket.getInputStream ()));
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
String message, modifiedMessage;
message = in.readLine ();
System.out.print("The received message from client: " + message);
modifiedMessage = message.toUpperCase();
out.print(modifiedMessage);
System.out.println ("\nModified message which is sent to client: " + modifiedMessage);
}
}
The server will have to receive a message from a client, then transforming it in an upper case string.
The client side is:
package com.company;
import java.io.*;
import java.net.*;
public class Main {
public static void main(String[] args) throws IOException {
Socket socket = new Socket("127.0.0.1", 1234);
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
System.out.println("Enter a lowercase sentence: ");
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
BufferedReader in = new BufferedReader((new InputStreamReader(socket.getInputStream())));
String messageSent = reader.readLine();
System.out.println("The message sent is: " + messageSent);
out.println(messageSent);
String messageReceived = in.readLine();
System.out.println("The modified message is: " + messageReceived);
}
}
I want the client to be able to print both the lower case sentence and the received (modified) upper case sentence. The problem is that, when I enter a simple word, say hello, my client will only print the original string, not the modified one.
The output of the server is:
The received message from client: hello
The modified message sent to the client is: HELLO
But the output of the client is:
The message sent is: hello
The modified message is: null
I know that the server is able to convert the string to the upper-case version and to connect to my client. Why doesn't my client print the received message? Doesn't it actually receive it?
You need to flush the message. PrintWriter calls flush in println, print doesn't.
on the server side you need to change to: out.println(modifiedMessage); instead of out.print(modifiedMessage);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With