user3235881
user3235881

Reputation: 497

Sharing variable in multithread

I try to implement a gateway who receive a command from the Client and execute it. If the Gateway receive the command SOPEN|127.0.0.5|12998|5 , he will open a channel ( socket ) to the server who have the ip 127.0.0.5 and will forward all the messages recieved from the client to this server. for example if the gateway receive the message MSG|127.0.0.1|12998|127.0.0.3|12897|blablabla if a channel is opened he will forward blablabla to the server and if not he will not do it. My problem is, if a client with IP address X opens a channel, another client with IP address Y can also use this channel. The gateway is usnig multithread, every client is running in a single thread, so how can I check if another Client have already an opened channel to the server ?

 public static void main(String args[]) {  
    try {  
        DatagramSocket serverSocket = new DatagramSocket(12890);;  
      while (true) {         

        ChildServer cServer = new ChildServer(serverSocket);  
        cServer.start();  
      }  
    } catch (IOException ex) {  
      System.out.println(ex);  
    }  

Class ChildServer

public void run() {  
           while(true)
            {
               byte[] receiveData = new byte[1024];
                byte[] sendData = new byte[1024];

                try
                {
                DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
                socket.receive(receivePacket);
                String sentence = new String( receivePacket.getData());
                System.out.println("RECEIVED:// " + sentence);
                InetAddress IPAddress = receivePacket.getAddress();
                int port = receivePacket.getPort();

                } catch (IOException e) {}

Upvotes: 0

Views: 93

Answers (1)

Yazan Jaber
Yazan Jaber

Reputation: 2078

Make a map and whenever a client sends SOPEN command add this client InetAdress and the InetAdress of the server into the map, now whenever you receive a new command you will get the server address from the map.

Upvotes: 2

Related Questions