3

There's a million examples on using Java sockets out there - and every one is the same! Every one shows a client socket being created, some text being sent, and the socket closed.

I am writing some test code. I want my client to loop round and send quite a few messages. It seems silly to close the client socket each time and re-create, so I thought I would just create one client socket, loop round and send data on the same socket. The thing is though - my server socket does not print out what it has received until the last message has been sent by the client and the client socket closed.

Server:

Socket  sock;
ClientConnection    client;

ServerSocket ss = new ServerSocket(portNumber);
ss.setSoTimeout(0); // 0=infinite

while (true) {
    sock = ss.accept();
    client = new ClientConnection(sock);
    new Thread(client).start();
    // ClientConnection reads from sock, prints, and closes sock
}

ClientConnection (a separate class on the Server side):

public class ClientConnection implements Runnable
{
    private Socket  m_socket;
    private BufferedReader m_in = null;

    public ClientConnection(Socket socket)
    {
        m_socket = socket;

        try {
            InputStream inStream = socket.getInputStream();
            m_in = new BufferedReader(new InputStreamReader(inStream));
        }
        catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }

    public String getMessage()
    {
        String line = null;
        StringBuffer    completeMessage = new StringBuffer();

        try {
            while ((line = m_in.readLine()) != null)
            {
                completeMessage.append(line);
            }
         }
         catch (IOException ioe) {
             ioe.printStackTrace();
             return "";
         }

         return completeMessage.toString();
    }

    public void run()
    {
        try {
            String message = getMessage();
            System.out.println("Received: " +message);
        }
        finally
        {
            try {
                m_socket.close();
            }
            catch (IOException ioe) {
                ioe.printStackTrace();
            }
        }
    }
}

Client:

socket = new java.net.Socket(m_destination, m_portNumber);
outputStream = socket.getOutputStream();
printStream = new java.io.PrintStream(outputStream);

while (more-stuff-to-send)
{
    printStream.print(text);
    printStream.print("\n");
    printStream.flush();
}

prinStream.close();
socket.close();

ClientConnection is created by the server when I start the client, but it does not print what has been sent until the client is done sending.

I feel like I'm missing the point somewhere along the line. Chat examples are quite common, so if I had a chat client then every message it wanted to send to a chat server it would create a client socket, send the message, and close the socket? Just doesn't seem right somehow.

Thank you.

2
  • wht does ClientConnection look like? side note, never use PrintStream wrapped around a Socket stream as it hide IOExceptions. Commented Mar 8, 2013 at 19:20
  • The ClientConnection code is imperative information in solving this problem. Perhaps you can post an <a href="sscce.org" title="SSCCE">SSCCE</a>? Commented Mar 8, 2013 at 19:34

1 Answer 1

-1
client = new ClientConnection(sock);

You are passing the socket in constructor.

so you shouldn't do:

socket = new java.net.Socket(m_destination, m_portNumber);

just cache that vatiable from contructor as : this.sock = sock; getting the reader and the writer is ok, also the server is ok.

I would use a Vector to be synchromized queue for sending messages, and the while (more-stuff-to-send) loop would check the queue and id empty than sleep, if has something to send, than pop the first and sent it while he must do stuff, or socket is closed my the client.

Sign up to request clarification or add additional context in comments.

3 Comments

note, it's not obvious from the code posted, but i believe the ClientConnection is a different class from the "client code" included (ClientConnection is a server-side class which maintains the connection to the client).
@jtahlborn for me it is obvious, more over I am doing alway like that, unless the customer / boss clearly saying they want something else. In most cases that is a perfect solution, other cases not.
You are mixing up client code and server code. The ClientConnection class is on the server side.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.