Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple client to server communication program in Java

I wrote a server-client communication program and it worked well.

Client module

import java.io.*;
import java.net.*;

class Client {
    public static void main(String argv[]) throws Exception {
        String sentence;
        String modifiedSentence;
      while(true){
        BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));

        Socket clientSocket = new Socket("myname.domain.com", 2343);

        DataOutputStream out = new DataOutputStream(clientSocket.getOutputStream());
        BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));

        System.out.println("Ready");
        sentence = in.readLine();
        out.writeBytes(sentence + '\n');
        modifiedSentence = in.readLine();
        System.out.println(modifiedSentence);
       }
      clientSocket.close();
    }
}

Server module

import java.net.*;

public class Server {
    public static void main(String args[]) throws Exception {
        String clientSentence;
        String cap_Sentence;
        ServerSocket my_Socket = new ServerSocket(2343);

        while(true) {
            Socket connectionSocket = my_Socket.accept();
            BufferedReader in = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
            DataOutputStream out = new DataOutputStream(connectionSocket.getOutputStream());
            clientSentence = in.readLine();
            cap_Sentence = "Raceived:" +  clientSentence + '\n';
            out.writeBytes(cap_Sentence);
        }
    }
}

The above is the code for a single client - server communication, now I want multiple client to interact with that server. I googled for it and found that it can be done with the use of a thread for each single client to talk to the server, but since I am a beginner I don't know exactly how to implement. So somebody please tell me how to do or give me some idea about it.

like image 777
kiddo Avatar asked Mar 24 '11 12:03

kiddo


People also ask

How do you handle multiple clients in socket programming in Java?

The method printToALLClients() sends the output to each client in the thread. For the Client, we use the Socket class and initiate the connection to a server bypassing the IP address and port number. We use the Scanner to get the input from the user and send the data to the server using the PrintWriter object.

Can multiple clients connect to same socket Java?

@asma, yes. Both clients can run on the same machine. Many clients can run on a single machine or multiple machines.

How do I connect two clients on a server?

Create a thread that will handle a ServerSocket to accept connections. Make the clients send a unique identificator to the server upon connection. When a client sends a message, use the id of the desired receiver client as a parameter, or empty so send to all clients.

How do you handle multiple clients in socket programming?

A better way to handle multiple clients is by using select() linux command. Select command allows to monitor multiple file descriptors, waiting until one of the file descriptors become active. For example, if there is some data to be read on one of the sockets select will provide that information.


2 Answers

MainServer class

public class Server {

    public static void main(String[] args) throws IOException {

        ServerSocket serverSocket = null;

        boolean listeningSocket = true;
        try {
            serverSocket = new ServerSocket(2343);
        } catch (IOException e) {
            System.err.println("Could not listen on port: 2343");
        }

        while(listeningSocket){
            Socket clientSocket = serverSocket.accept();
            MiniServer mini = new MiniServer(clientSocket);
            mini.start();
        }
        serverSocket.close();       
    }

}

Helper Class

public class MiniServer extends Thread{

    private Socket socket = null;

    public MiniServer(Socket socket) {

        super("MiniServer");
        this.socket = socket;

    }

    public void run(){
            //Read input and process here
    }
            //implement your methods here

}
like image 79
o12 Avatar answered Sep 21 '22 13:09

o12


You want to look into Java concurrency. That's the concept of one Java program doing multiple things at once. At a high level you will be taking your while(true) { //... } block and running it as part of the run() method of a class implementing Runnable. You'll create instances of Thread that invoke that run() method, probably one per client you expect.

For a really good, deep understanding of all that Java offers when it comes to concurrency, check out Java Concurrency in Practice.

like image 22
justkt Avatar answered Sep 22 '22 13:09

justkt