2

I'm in the process of writing a messaging program, and I'm running into a spot where I'm having trouble understanding how to pass a socket over to a new thread for handling outbound messages via TCP. I'm currently using UDP packets for messages coming from a client, to the server, which, being UDP, doesn't require very much processing, as it's simply listening for incoming packets, before it de-serializes the objects, and processes them as needed in a separate thread. My problem now is, I'm setting up a client initiated TCP socket for reverse traffic, from the server to the assorted clients that connect. I've done a bit of research, and I already understood that each client should have their own thread for handling outgoing messages, along with another thread simply for accepting the incoming connections. I'm unsure of how to actually achieve this, and I've done some research into the topic.

I've found this: http://docs.oracle.com/javase/tutorial/networking/sockets/clientServer.html

The resource above basically verified my original suspicion that this would have to be handled by threads dedicated to the client. They included psuedo code here, which is representing my listener thread.

while (true) {
    accept a connection;
    create a thread to deal with the client;
}

I'm a bit of a visual learner, and I have been searching for some type of an example where this is done. I'm unsure of what variable I'd be passing over to the thread that keeps the original connection open, and pushes data back to clients. I'm also having a little bit of trouble grasping whether it even keeps the same socket open, or if a new one needs to be established, which then, makes me believe a firewall could interfere, but I know that won't be the case.

Can somebody explain this for me in detail? If possible, an example would be greatly appreciated!

I'll be likely replying and commenting on responses in about 15-30 minutes from the time this is posted.

2
  • There are plenty of examples everywhere. Start with the Custom Networking section of the Oracle Java Tutorial. Commented Nov 6, 2014 at 22:24
  • Correct me if I'm wrong, but isn't that the resource I just posted in the question? I've been looking for things like tutorials, and all I've found are simple 1 to 1 communication, as apposed to 1 to many. Also, the code block i included was from that exact same tutorial. I'm asking for help understanding how to implement this, and I've already went through what you said to look at before even creating this question. Commented Nov 6, 2014 at 22:42

1 Answer 1

2

What you are doing sounds correct. I typically implement a server like this (simplified version with no tracking of the clients and so on):

@Override
public void run() {
    //start listening on the port
    try {
        serverSocket = new ServerSocket(port);
        logger.info("Listening for connections on port " + port);
    } catch (IOException e) {
        logger.error("Cannot start SocketListener on port " + port + ". Stopping.", e);
        return;
    }

    while (!stopped) {
        try {
            //wait for connection
            Socket newSocket = serverSocket.accept();
            ClientThread client = new ClientThread(newSocket);
            Thread clientThread = new Thread(client, MEANINGFUL_THREAD_ID);
            clientThread.start();
        } catch ...
    }
}

where serverSocket is a ServerSocket instance variable and stopped is a flag I use to stop the listener thread.

So to answer your questions in the comment, you normally pass the Socket object to each client thread so that that thread can work with the input and output stream and handle closing of the socket and so on. Once you "accept" a socket connection, you do not need to recreate the ServerSocket, you simply call .accept() again to start waiting for a new connection.

In most cases, you will need to keep track of all client threads in your server so that you can stop the server gracefully or do broadcasts for example.

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

1 Comment

Thanks for clearing this up for me. For some reason, I had the feeling that you couldn't just pass a single instance of a socket to another thread, re-establish a new connection with someone else, and have that other thread working fine. Nor did I know how to pass it correctly.

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.