Question

I wrote code can send a message to server. Problem is if I capture communication in Wireshark my string message sent from my application looks like this:

hello    - 1 packet

If I check the same message sent from Telnet cmd terminal message looks like this:

h      - 1 packet
e      - 1 packet
l      - 1 packet
l      - 1 packet
o      - 1 packet

So finally it sent entire string by character. Server can read the message from cmd Telnet terminal and reply but can't read the message sent from my application. Is there some way how can I send string like this? I'm not programming server. I'm programming only client side so it's important server has to able read the message correctly. Thanks a lot!

PrintWriter out;
BufferedReader in;

 public void run() {
                // TODO Auto-generated method stub
                try {
                    InetAddress serverAddr = InetAddress.getByName(hostname);

                    // create a socket to make the connection with the server
                    socket = new Socket(serverAddr, port);
                    Log.i("Terminal", "Socket connecting");

                    try {

                        // send the message to the server
                        out = new PrintWriter(
                                new BufferedWriter(new OutputStreamWriter(
                                        socket.getOutputStream())), true);

                        Log.i("Terminal", "Connected.");
                        // receive the message which the server sends back
                        in = new BufferedReader(new InputStreamReader(
                                socket.getInputStream()));

                     }catch...
               }catch...
 }

//send code
public void sendMessage(String message) {
        if (out != null && !out.checkError()) {
            out.println(message);
            out.flush();
            Log.i("Terminal", "Message sent.");
        }
}
Was it helpful?

Solution

Why not just send each character separately?

Something like this:

public void sendMessage(String message) {
    for (String ch : message.split(""))
        sendPacket(ch);
    sendPacket("\r\n");
}

public void sendPacket(String payload) {
    if (out != null && !out.checkError()) {
        out.print(payload);
        out.flush();
        Log.i("Terminal", "Message sent.");
    }
}

You said everything was working fine, but if you do run in to issues with packet coalescing in the future you can disable the Nagle algorithm by adding this line:

socket.setTcpNoDelay(true);

right after this one:

socket = new Socket(serverAddr, port);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top