I have a server and a client(say client1) both on a single file working perfectly. I have a situation like: I have another client(say client2) which sends information to the server. This server has to send the information taken from client2 to client1. But when I used same port number and same IP Address on both the server and client1 when I try to send information from client2, the client1 is also accepting at a time.
How can I send the information from client2 so that first server first accepts it and then sends that information to client1?
Client2 Code:
import java.io.*; import java.net.*; class Client1 { public static void main(String[] args)throws Exception { try { InetAddress ip=InetAddress.getByName("228.5.6.7"); int port=4270; MulticastSocket sock=new MulticastSocket(); String msg="Hello All"; DatagramPacket packet; while(true) { packet =new DatagramPacket(msg.getBytes(),msg.length(),ip,port); sock.send(packet); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } My Server and Client Code:
class Server implements Runnable { public void run() { try { //get the multicast ip InetAddress ip = InetAddress.getByName("228.5.6.7"); int port=4270; byte[] buffer=new byte[100]; byte[] data = null; MulticastSocket sock=new MulticastSocket(port); //join the multicast group sock.joinGroup(ip); while(true) { //create a datagram packet in which u will receive the msg Thread.sleep(2000); DatagramPacket pack=new DatagramPacket(buffer,buffer.length); sock.receive(pack); String msg = new String(buffer); System.out.println("Sever Has Received :" +msg); //SENDING THE MESSAGE TO CLIENT System.out.println("Sending the Message!!!"); data = msg.getBytes(); DatagramPacket pack1 = new DatagramPacket(data,msg.length(),ip,port); Thread.sleep(2000); sock.send(pack1); } } catch (Exception ex) { Thread t = Thread.currentThread(); t.getUncaughtExceptionHandler().uncaughtException(t, ex); } } } Client1 Code:
class Client implements Runnable { public void run() { try { InetAddress address1 = InetAddress.getByName("228.5.6.7"); int port=4271; MulticastSocket socket1 = new MulticastSocket(port); //join a Multicast group and send the group salutations socket1.joinGroup(address1); byte[] data1 = new byte[256]; DatagramPacket packet1 = new DatagramPacket(data1,data1.length); while(true) { // receive the packets socket1.receive(packet1); String str = new String(packet1.getData(),0,packet1.getLength()); Thread.sleep(2000); System.out.println("Client Received : "+str); } } catch (Exception ex) { Thread t = Thread.currentThread(); t.getUncaughtExceptionHandler().uncaughtException(t, ex); } } } MAIN PROGRAM
class ClientAndServer { public static void main(String[] args) { Server s = new Server(); //First start Server and then Start client Thread t1 = new Thread(s); t1.start(); Client c = new Client(); Thread t2 = new Thread(c); t2.start(); } }