在同一LAN上多播C ++多台计算机

时间:2015-10-07 15:40:21

标签: java c++ sockets udp multicast

我正在为大学工作,我被要求为我大学的局域网实施聊天。 我正在使用多播来向组中的所有注册用户发送相同的消息。我的发件人是在C ++和java上的接收器上开发的。在同一台计算机上进行测试时,我附加的代码工作正常,发送方发送,接收方接收,但在另一台计算机上运行客户端时,它不会收到发送的消息。

服务器:

int main(){

/** MC socket **/

struct sockaddr_in groupSock;
groupSock.sin_family = AF_INET;
groupSock.sin_addr.s_addr = inet_addr("225.5.4.30");
groupSock.sin_port = htons(54321);
    bzero(&(groupSock.sin_zero),8);

int mcsock;
if ((mcsock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1) {
        perror("Socket MC");
        exit(1);
    }

int nroM = 0;
while(1)
{
    fflush(stdout);

    stringstream resp; 
    resp << "Mensaje multicast: " << nroM << "\n";
    cout << resp.str();
    /* Send a message to the multicast group specified by the*/
    /* groupSock sockaddr structure. */
    /*int datalen = 1024;*/
    if(sendto(mcsock, resp.str().c_str(), strlen(resp.str().c_str()), 0, (struct sockaddr*)&groupSock, sizeof(groupSock)) < 0)
    perror("Sending datagram message error");
    nroM++;
    sleep(2);
}

close(mcsock);
    return 0;

} 

客户端:

class UDPCliente {
public static void main(String args[]) throws Exception{

InetAddress address = InetAddress.getByName("225.5.4.30");
// Create a buffer of bytes, which will be used to store
// the incoming bytes containing the information from the server.
// Since the message is small here, 256 bytes should be enough.
byte[] buf = new byte[256];
// Create a new Multicast socket (that will allow other sockets/programs
// to join it as well.
try (MulticastSocket clientSocket = new MulticastSocket(54321)){
    //Joint the Multicast group.
    clientSocket.joinGroup(address);
    while (true) {
    // Receive the information and print it.
    DatagramPacket msgPacket = new DatagramPacket(buf, buf.length);
    clientSocket.receive(msgPacket);
    String msg = new String(buf, 0, buf.length);
    System.out.print(msg);
    }
} catch (IOException ex) {
    ex.printStackTrace();
}
}

仅提供额外信息,此代码包含适当的导入,包括编译和运行。

谢谢!

1 个答案:

答案 0 :(得分:0)

好吧,显然我换了另一台电脑并且代码工作了。所以防火墙有事可做。我回答如此,如果有人需要同样的问题,我附加的代码如果包括和导入适当的库,将完美地工作!!