0

I have 2 classes, a server and a client. The server uses multiple threads to accept many clients. So x clients can join the same server. However in an attempt to identify the threads from the client method, I seem to have found that its not making multiple threads as the ID are the same for all clients. The code I have is as follows:

SERVER:

public class Server
{
    ServerSocket serverSocket;
    int portNumber;
    public static volatile String userInput;
    public volatile int noOfClients = 0;

public static void main(String[] args)
{
    Server s = new Server();
    s.startup();
}


/**
 * Start the server on the user picked port
 */
public void startup()
{   
    try 
    {
        System.out.println("Enter a port");
        Scanner dif = new Scanner(System.in);
        portNumber = Integer.parseInt(dif.nextLine());
        dif.close();

        serverSocket = new ServerSocket(portNumber);
        newThread();
    }
    catch (IOException e) {
        System.out.println("Error");
        System.exit(0);
    }
}


public void newThread()
{
    Thread thread =new Thread()
    {

        public void run()
        {   
            while(true) {
                try {

                    accept();
                } catch (Exception e) {
                    System.out.println("Error");
                }
            }
        }
    };
    thread.start();
}

public void accept()
{
    try
    {
        Socket clientSocket = serverSocket.accept();
        new Thread(new ClientSocket(clientSocket)).start();
        System.out.println("A new client has just connected.");
        noOfClients++;

    } catch(IOException e)
    {
        System.out.println("Error");
        System.exit(0);
    }
}


class ClientSocket implements Runnable {
    Socket clientSocket;

    public ClientSocket(Socket clientSocket) {
        this.clientSocket = clientSocket;
    }

    public void run() {
        {
            try
            {
                PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);                   
                BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));

                while (true)
                {
                    userInput = in.readLine();
                }

            } catch (IOException e)
            {
                System.out.println("Error");
            }
        }
    }
}
}

CLIENT:

public class Client
{
    Socket clientSocket;
    public static int threadName;


public static void main(String[] args) throws IOException {
    String hostName = args[0];
    int portNumber = Integer.parseInt(args[1]);


    try {
        Socket serverSocket = new Socket(hostName, portNumber);
        PrintWriter out = new PrintWriter(serverSocket.getOutputStream(), true);
        BufferedReader in = new BufferedReader(new InputStreamReader(serverSocket.getInputStream()));
        BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));

        Thread thread = Thread.currentThread();
        System.out.println("RunnableJob is being run by " + thread.getName() + " (" + thread.getId() + ")");
        String userInput;

        while ((userInput = stdIn.readLine()) != null)
        {

            out.println(userInput);
            System.out.println("Server: " + userInput);
        }

    } catch(UnknownHostException e) {
        System.out.println("error in host");
    } catch(IOException e) {
        System.out.println("error in IO");
    }


}
}

When running two separate clients, the

System.out.println("RunnableJob is being run by " + thread.getName() + " (" + thread.getId() + ")");

line of code prints out the same. How can i fix it so that each new client connection is started within is own UNIQUE thread. so 2 clients will have 2 threads in total? Thanks :)

  • 2
    You're printing the thread names on the client. Don't you want to know the thread names in your server program? – spinlok Mar 31 '14 at 01:53
  • I think you meant to check the threads within the server, not the client. – Kyle Spencer Mar 31 '14 at 01:56
  • @spinlok What Im wanting to do is if the thread is ID=1 do this... else do nothing, then increments to if ID=1 do this... and so on. So basically I am wanting to uniquely identify the threads and only do something with one at a time, then do the same to the next and so on. Hope that makes sense –  Mar 31 '14 at 01:57
  • @KyleSpence just moved that line into the server and it is giving seperate ID's. i have thought of a way I can do what I was wanting from the server class not the client, thanks for the help! –  Mar 31 '14 at 02:00
  • So you want to uniquely identify clients based off of their thread id? Since they are in different runtimes, they are separate from each other. – Kyle Spencer Mar 31 '14 at 02:00

2 Answers2

1

First, you are checking the thread ids for the clients, which are separate from each other, so that won't work.

However using a thread id is not a very good way to identify clients. Instead why don'y you keep a count of the number of clients, then when a new one joins, increment the number and give the client object that number as an id.

Kyle Spencer
  • 323
  • 1
  • 8
0

Multiple clients will connect at different port no with server. You can use that port no to distinguish between clients.

You can store ClientSocket some where to retrieve other information of each client in future if needed as shown in below code.

Here is the code:

private static HashMap<Integer, ClientSocket> clientInfo = new HashMap<Integer, ClientSocket>();
class ClientSocket implements Runnable {
    Socket clientSocket;

    public ClientSocket(Socket clientSocket) {
        this.clientSocket = clientSocket;
        System.out.println(clientSocket.getPort());
        clientInfo.put(clientSocket.getPort(), this);
    }
    ...

Read more about Java Server with Multiclient communication.

Community
  • 1
  • 1
Braj
  • 46,415
  • 5
  • 60
  • 76
  • 1
    Multiple clients can connect to a server with different port numbers, and multiple clients can connect to a server [with the same port number](http://docs.oracle.com/javase/tutorial/networking/sockets/clientServer.html). The server can be set up to work either way. – Gilbert Le Blanc Mar 31 '14 at 08:30
  • Yes you are absolutely right. Now it depends where you want to implement the logic. – Braj Mar 31 '14 at 08:34