简体   繁体   中英

Java UDP Multicast

I had a simple unicast client/server program working with the client asking something from the server and the server answering. Now I want to do a variant, but adding Multicast to it. At this stage, the Client is able to join a group and receive a confirmation like:

hostAddr is /192.168.56.1 and PORT NUMBER IS: 54767

On the server side, I'm expecting a package from a client, but I never get it.

Server Code:

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.MulticastSocket;
import java.util.HashMap;

public class MulticastServer
{
public static MulticastSocket socket;

final static InetSocketAddress d = new InetSocketAddress("239.1.1.3", 4444);

public static void runNotifier(String m_addr, int m_port)
{
    //final InetSocketAddress d = new InetSocketAddress(m_addr, m_port);
    (new Thread()
    {
        public void run()
        {
            while(true)
            {
                try {
                    sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                byte[] hello = ("hello").getBytes();
                DatagramPacket h = new DatagramPacket(hello, hello.length, d.getAddress(), d.getPort());
                //System.out.println("ADDR: " + d.getAddress() + " PORT: " + d.getPort());
                try {
                    //System.out.println("SENDING");
                    socket.send(h);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    ).start();

}

public static void initSocket(int port) throws IOException
{
    socket = new MulticastSocket(); //port
    socket.setTimeToLive(1);
}

public static void main(String args[]) throws Exception
{
    initSocket(4444);
    runNotifier("239.1.1.3", 4444);
    HashMap<String, String> cache = new HashMap<String, String>();
    DatagramSocket serverSocket = new DatagramSocket(4444);  

    byte[] receiveData = new byte[1024]; //buffers           
    byte[] sendData = new byte[1024];  
    System.out.println("BEFORE SERVER WHILE");
    while(true)
    {   
        System.out.println("INSIDE SERVER WHILE");
       DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);                   
       serverSocket.receive(receivePacket);
       System.out.println("RECEIVED FROM CLIENT");
       //recebe string do cliente
       String sentence = new String(receivePacket.getData(),0, receivePacket.getLength());
       /*
       String[] parts = sentence.split(" "); 

       if (sentence.contains(" ")) {                       
           cache.put(parts[1], parts[2]);
        } else {
           System.out.println("SERVER can't do anything with this."); 
        }

       //String name = cache.get(parts[1]);
       */
       System.out.println("CLIENT SAID: " + sentence);
       //System.out.println("THE NAME IS: " + name);

       InetAddress IPAddress = receivePacket.getAddress();                   
       int port = receivePacket.getPort();                   
       String capitalizedSentence = sentence.toUpperCase();                   
       sendData = capitalizedSentence.getBytes();                  
       DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port);                   
       serverSocket.send(sendPacket);
       receiveData = null;
       }
}
}

Client Code

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

public class MulticastClient {

public static  MulticastSocket socket = null;

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

    socket = new MulticastSocket(4444); //multicast port
    InetAddress address = InetAddress.getByName("239.1.1.3"); //multicast address
    socket.joinGroup(address);
    System.out.println("JOINED GROUP");
    //recebe o hello
    byte[] a = new byte[1024];
    DatagramPacket p = new DatagramPacket(a, a.length);
    socket.receive(p);
    System.out.println("RECEIVED PACKAGE");
    InetAddress hostAddr = p.getAddress();
    int portNumber = p.getPort();
    System.out.println("hostAddr is " + hostAddr + " and PORT NUMBER IS: " + portNumber);
    //

    HashMap<String, String> cache = new HashMap<String, String>();
    //DatagramSocket serverSocket = new DatagramSocket(p.getPort());            

    byte[] receiveData = new byte[1024]; //buffers           
    byte[] sendData = new byte[1024];    

   /* DatagramPacket packet;
    byte[] buf = new byte[256];
    packet = new DatagramPacket(buf, buf.length);
    socket.receive(packet);*/

    //escrita consola
    BufferedReader inFromUser =  new BufferedReader(new InputStreamReader(System.in)); 
    String sentence = inFromUser.readLine();      
    sendData = sentence.getBytes(); 

    DatagramSocket clientSocket = new DatagramSocket();       

    DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, hostAddr, portNumber);      
    clientSocket.send(sendPacket);       
    System.out.println("SENT TO SERVER");
    DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);       
    clientSocket.receive(receivePacket);       

    String modifiedSentence = new String(receivePacket.getData());       
    System.out.println("SERVER: " + modifiedSentence);       
    clientSocket.close();        

socket.leaveGroup(address);
socket.close();
}

}

My best guess so far is that in line 53 of the server

DatagramSocket serverSocket = new DatagramSocket(4444); 

I'm using an incorrect port number. If the client received port 54767 then it will send to that port. But even assuming that is the problem, I don't know how to fix it, since everytime I run it, the Client gets a different port.

Another problem I have is that I can't seem to run two Clients at once due to error

Exception in thread "main" java.net.SocketException: Unrecognized Windows Sockets error: 0: Cannot bind

In line 12 of the Client

socket = new MulticastSocket(4444); //multicast port

Thanks in advance for your time.

1- You can create a MulticastSocket on the server side to receive messages.
2- I think you don't need DatagramSocket to communicate with others in the gorup, because MulticastSocket works well for client and server. Binding Error which caused on line 12 related to it.

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