CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 10 of 10
  1. #1
    Join Date
    Apr 2010
    Posts
    4

    Multithreading with sockets

    I was given an assignment to code a simple console based chat program in java with multiple users using threads and sockets. The way I have chosen to implement this is to have the client side program first query the server via a hardcoded port # for an open port for which to connect to the server. Then with the fresh port # in hand the client closes that socket, freeing it up for another client to query the server, and opens up a new socket with the dedicated port.

    My problem is the client never makes the second connection. I have verified that the server is "listening" to the right port number and that the client is attempting the connect to the right port number. But I get a connection error each time. Is there a rule about sockets I dont know? Can you not initiate more than 1 in any thread? If so, should I be spinning a thread off the client to initiate the first contact? I can supply the code if necessary.

    Also (this is the multithreaded part) the server is designed to dish out the port numbers then assign each number to a new socket and pass it to a new thread to handle. But when it passes the socket off, the server no longer is connected to it. So how do I get the messages sent from each client to each other client concurrently?

    Once again I can provide code if necessary.

  2. #2
    Join Date
    Apr 2010
    Location
    Dayton, OH
    Posts
    16

    Re: Multithreading with sockets

    It's been a very long time since I've played with JAVA, so there may be some restrictions in JAVA I'm unaware of. That said, there is no reason you can't have multiple sockets per thread as they're independent objects. A single thread per socket can just be an easier way to handle multiple clients simultaneously. You can, however, server a large number of clients with a single thread if architected correctly.

    Along the same lines, you can also have multiple clients connected to the same socket on the server side. As long as the remote end point is different (client IP and source port), it doesn't matter how many clients sockets are connected to your server port. ServerSocket, for example, uses an accept() method to return a new socket for each client that connects. You can then use this socket to communicate with that client and call the ServerSocket's accept method again to listen for another client.

    Although this doesn't directly answer your questions, an architecture like this may make it so you don't even have to worry about the disconnected problems anymore.

  3. #3
    Join Date
    Feb 2005
    Posts
    2,160

    Re: Multithreading with sockets

    This should probablly be moved to the networking forum as it has little to do with threading in general, and not germane to the premise this forum.

    That said, a TCP/IP server process should use bind() to connect to a socket on a specific port, then call listen() to wait for connections. Once a client has connected, call accept() to create a new socket for the client and then pass this socket off to a thread to handle the client/server traffic from that point. There's probably thousands of examples on the net.

  4. #4
    Join Date
    Apr 2010
    Posts
    4

    Re: Multithreading with sockets

    Ok ill post the code, that might make it easier...
    Dont be to harsh its not refined or anything, more like smash and grab.


    This would be the client side
    Code:
    import java.net.*;
    import java.io.*;
    import java.util.*;
    
    public class SockClient
    {
    	private static Socket chatCon = null, portGetter = null;
    	private static PrintWriter sendThis = null;
    	private static BufferedReader bin = null;
    	private static InputStream in = null;
    	private static int portID = 0;
    	
    	public void setPortID(int newID)
    	{	portID = newID;	}//setPortID
    	
    	public static void main(String[] args)
    	{
    		Scanner keyboard = new Scanner(System.in);
    		String line, message;
    		boolean isRunning = false;
    		portID = getPortNum();
    		try
    		{
    			if(portID > 0)
    				isRunning = true;
    			System.out.println(portID);
    			chatCon = new Socket("***.***.***.***", portID);
    			sendThis = new PrintWriter(chatCon.getOutputStream(), true);
    			in = chatCon.getInputStream();
    			bin = new BufferedReader(new InputStreamReader(in));
    			while(isRunning)
    			{
    				System.out.print("User >: ");
    				message = keyboard.next();
    				sendThis.println(message);
    				
    				if((line=bin.readLine()) != null)
    					System.out.println(line);
    				
    			}//while
    		}//try
    		catch (IOException ioe)
    		{
    			System.err.println(ioe);
    		}//catch
    		finally
    		{
    			try
    			{
    				chatCon.close();
    				sendThis.close();
    				in.close();
    				bin.close();
    			}//try
    			catch (IOException ioe)
    			{
    			System.err.println(ioe);
    			}//catch
    		}//finally
    		
    	}//main
    	
    	public static int getPortNum()
    	{
    		int port = 0;
    		String portString;
    		try
    		{
    			portGetter = new Socket("***.***.***.***", ****);
    			in = portGetter.getInputStream();
    			bin = new BufferedReader(new InputStreamReader(in));
    			portString = bin.readLine();
    			port = Integer.parseInt(portString);
    		}//try
    		catch(IOException ioe)
    		{
    			System.out.println(ioe);
    		}//catch
    		finally
    		{
    			try
    			{
    				portGetter.close();
    				in.close();
    				bin.close();
    			}//try
    			catch(IOException ioe)
    			{
    				System.out.println(ioe);
    			}//catch
    		}//finally
    		return port;
    	}//getPortNum
    }//SocketClient

    And this is what the server looks like...
    Code:
    import java.net.*;
    import java.io.*;
    
    public class SockServer
    {
    	private static final int BASE_PORT = ****;
    	private static int currentPortID_ = BASE_PORT + 1;
    	private static int count_ = 1;
    	private static boolean isRunning_ = true;
    	private static ServerSocket chatServ_ = null, request_ = null;
    	private static Socket retriever_ = null;
    	private static PrintWriter portNum_ = null;
    	
    	public static void main(String[] args)
    	{
    		try
    		{
    			request_ = new ServerSocket(BASE_PORT);
    		}//try
    		catch (IOException ioe)
    		{
    			System.err.println(ioe);
    		}//catch
    		while(isRunning_)
    		{
    			try
    			{
    				retriever_ = request_.accept();
    				portNum_ = new PrintWriter(retriever_.getOutputStream(), true);
    				portNum_.println(currentPortID_);
    				request_.close();
    				
    				chatServ_ = new ServerSocket(currentPortID_);
    				retriever_ = chatServ_.accept();
    				ChatThread client = new ChatThread(retriever_);
    				client.start();
    				currentPortID_++;
    			}//try
    			catch (IOException ioe)
    			{
    				System.err.println(ioe);
    			}//catch
    			finally
    			{
    				try
    				{
    					chatServ_.close();
    				}//try
    				catch (IOException ioe)
    				{
    					System.err.println(ioe);
    				}//catch
    			}//finally
    		}//while
    		try
    		{
    			request_.close();
    		}//try
    		catch (IOException ioe)
    		{
    			System.err.println(ioe);
    		}//catch
    	}//main
    }//class
    This results in a refused connection ONLY for the second connection. Why? The first socket always work, second one always fails...

  5. #5
    Join Date
    Feb 2005
    Posts
    2,160

    Re: Multithreading with sockets

    Ack! I thought the OP was porting Java to C++.

  6. #6
    Join Date
    Apr 2010
    Posts
    4

    Re: Multithreading with sockets

    Well the languages are similar in syntax...Im not asking for corrections, just want to make sure im not crazy and the logic is right.

  7. #7
    Join Date
    May 2000
    Location
    KY, USA
    Posts
    18,652

    Re: Multithreading with sockets

    [Moved thread to appropriate forum]

  8. #8
    Join Date
    Nov 2002
    Location
    California
    Posts
    4,556

    Re: Multithreading with sockets

    Quote Originally Posted by awri View Post
    ...The way I have chosen to implement this is to have the client side program first query the server via a hardcoded port # for an open port for which to connect to the server. Then with the fresh port # in hand the client closes that socket, freeing it up for another client to query the server, and opens up a new socket with the dedicated port.
    As mentioned by Night_Wulfe, this is not the way sockets are designed to work. A server can accept many incoming connections on the exact same port. There is no need to negotiate a separate port number for each client.

    Mike

  9. #9
    Join Date
    Apr 2010
    Posts
    4

    Re: Multithreading with sockets

    So even though many inputs are incident upon the same port, as long as each client has its own thread, all the messages will get to the server?

    That being said, another question arises that I havn't dealt with yet. How do I take the messages and deliver them to the now independent threads?

  10. #10
    Join Date
    Nov 2002
    Location
    California
    Posts
    4,556

    Re: Multithreading with sockets

    Quote Originally Posted by awri View Post
    So even though many inputs are incident upon the same port, as long as each client has its own thread, all the messages will get to the server?
    A slight re-write of your question, for clarity: "... as long as the server has one thread for each client, all messages will get to the server?"

    Yes.

    That being said, another question arises that I havn't dealt with yet. How do I take the messages and deliver them to the now independent threads?
    Maybe this will help: "Socket Communications: Example 2: Multithreaded Server Example" at http://java.sun.com/developer/online...ket.html#multi

    Very similar code can be found here, but with a slightly more extensive discussion of the code: "Multithreaded Server in Java" at http://tutorials.jenkov.com/java-mul...ed-server.html

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured