Razor Storm
Razor Storm

Reputation: 12336

TCP Client/Server communication only sends first message?

I am setting up a simple TCP Client Server interaction in java.

Server:

The server is a desktop client written in Java:

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

class TCPServer
{
    public static int PORT_NUMBER = 6129;

    public static void main(String argv[]) throws Exception
    {
        String clientMessage;
        ServerSocket welcomeSocket = new ServerSocket(PORT_NUMBER);

        while (true)
        {
            Socket connectionSocket = welcomeSocket.accept();

            BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));

            DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());

            clientMessage = inFromClient.readLine();

            System.out.println("Received: " + clientMessage);

            outToClient.writeBytes("I received this: "+ clientMessage +"\n");
        }
    }
}

Client:

The client is an android app that connects to the server with TCP. In the client I have a method sendMessage(String msg) which attempts to send a message to the server.

public static void sendMessage(String msg) throws IOException
{
    if (mainSocket == null)
    {
        return;
    }
    if (!mainSocket.isConnected())
    {
        connectSocket();
    }
    PrintWriter output = new PrintWriter( mainSocket.getOutputStream());
    output.println(msg);
    output.flush();
    System.out.println(msg);
}

The problem is, the server receives the first message, but any subsequent messages won't show up at all. When I close the client down, all of a sudden all the other messages show up at once in the server.

This is what the server sees:

Received: message 1

No activity for a long time...
Then I shut down the client

Received: message 2 message 3 message 4 message 5 etc..

I put a println in the sendMessage() method, and the method itself is being called in real time.

Upvotes: 3

Views: 9166

Answers (1)

emboss
emboss

Reputation: 39620

You need to explicitly close() your PrintWriter on the client side each time you send a message. Same on the server side when you are done reading inFromClient, and again when you are done writing to outToClient.

See also this basic example, they explain the basic workflow quite nicely:

However, the basics are much the same as they are in this program:

Open a socket.

Open an input stream and output stream to the socket.

Read from and write to the stream according to the server's protocol.

Close the streams.

Close the socket.

Upvotes: 6

Related Questions