简体   繁体   中英

Server with Multiple Clients - JAVA

Given the two codes , one for the server and the other one for the client , i am trying to make multiple clients communicate with the server but i don't have a clue how to do it. Any idea how the server can recognize the client who spoke to him and reply back to the same client ?

Server:

    import java.io.*;
    import java.net.*;
    public class Provider{
    ServerSocket providerSocket;
    Socket connection = null;
    ObjectOutputStream out;
    ObjectInputStream in;
    String message;
    Provider(){}
    void run()
{
    try{
        //1. creating a server socket
        providerSocket = new ServerSocket(2004, 10);
        //2. Wait for connection
        System.out.println("Waiting for connection");
        connection = providerSocket.accept();
        System.out.println("Connection received from " + connection.getInetAddress().getHostName());
        //3. get Input and Output streams
        out = new ObjectOutputStream(connection.getOutputStream());
        out.flush();
        in = new ObjectInputStream(connection.getInputStream());
        sendMessage("Connection successful");

        //4. The two parts communicate via the input and output streams
        do{
            try{
                message = (String)in.readObject();

                System.out.println("client>" + message);
                if (message.equals("byee"))
                    sendMessage("Wosil");
            }
            catch(ClassNotFoundException classnot){
                System.err.println("Data received in unknown format");
            }
        }while(!message.equals("bye"));
    }
    catch(IOException ioException){
        ioException.printStackTrace();
    }
    finally{
        //4: Closing connection
        try{
            in.close();
            out.close();
            providerSocket.close();
        }
        catch(IOException ioException){
            ioException.printStackTrace();
        }
    }
}
void sendMessage(String msg)
{
    try{
        out.writeObject(msg);
        out.flush();
        System.out.println("Zame-Server>" + msg);
    }
    catch(IOException ioException){
        ioException.printStackTrace();
    }
}
public static void main(String args[])
{
    Provider server = new Provider();
    while(true){
        server.run();
        }
    }
}

Client

import java.io.*;
import java.net.*;
public class Requester{
Socket requestSocket;
ObjectOutputStream out;
ObjectInputStream in;
String message;
Requester(){}
void run()
{
    try{
        //1. creating a socket to connect to the server
        requestSocket = new Socket("localhost", 2004);
        System.out.println("Connected to localhost in port 2004");
        //2. get Input and Output streams
        out = new ObjectOutputStream(requestSocket.getOutputStream());
        out.flush();
        in = new ObjectInputStream(requestSocket.getInputStream());
        //3: Communicating with the server

                sendMessage("Hi my server");
                sendMessage("SENDING");
                message = "byee";
                sendMessage(message);
        do{
            try{
                message = (String)in.readObject();
                System.out.println("server>" + message);


            }
            catch(ClassNotFoundException classNot){
                System.err.println("data received in unknown format");
            }
        }while(!message.equals("bye"));
    }
    catch(UnknownHostException unknownHost){
        System.err.println("You are trying to connect to an unknown host!");
    }
    catch(IOException ioException){
        ioException.printStackTrace();
    }
    finally{
        //4: Closing connection
        try{
            in.close();
            out.close();
            requestSocket.close();
        }
        catch(IOException ioException){
            ioException.printStackTrace();
        }
    }
}
void sendMessage(String msg)
{
    try{
        out.writeObject(msg);
        out.flush();
        System.out.println("Zame-Client>" + msg);
    }
    catch(IOException ioException){
        ioException.printStackTrace();
    }
}
public static void main(String args[])
{
    Requester client = new Requester();
    client.run();
}
}

not sure if i understand your question correctly, but i think you want multiple clients to communicate with the server concurrently . to do this, you will need to know how to use threads. when the server makes a connection to a client, this connection must run in it's own thread. then it will be ready to accept new client connections. if you do this correctly, you will be able to run the server once, and have many clients connect to the server.

There seems to be 2 sides to your question. The first deals with concurrency (how to launch multiple clients and make them communicate with the server). For that you have to have a basic knowledge of threads in Java.

The second part of your question: how for the server to keep track of multiple clients (this also suggest that your communication between client and server is stateful): You might want to design a simple protocol, through which client and server communicate. For example, when a client communicates with the server it has to stamp its messages with a unique identifier. The server uses that identifier to track and keep hold of whatever resources it has to use to fulfil tasks, the client asks of it (if that is at all mandated by your requirements).

Kryonet is a very good Java library which provides a clean and simple API for efficient TCP and UDP client/server network communication using NIO.

It will make your network programming work a lot more easier, and you can get a better understanding of how to write client and server side code.

I would suggest that you try out your network programming skills using this library.

You need not even hard code any IP address of the server while in LAN. The clients can discover the server in just one line of code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM