Unity UDP组播

2018-01-15  本文已影响75人  LeoYangXD
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using UnityEngine;


public class UDPClientMul : MonoBehaviour
{
    UdpClient Sendclient;
    //  Socket socket;
    static UdpClient ReceiveClient;
    IPEndPoint SendPort;
    IPEndPoint ReceivePort;
    Thread t;
    int i;
    public string msgNma = "Yang";
    public TextMesh textShow;
    void Start()
    {
        Sendclient = new UdpClient();
    //发送信息的端口一定要和接受的端口号一样
    SendPort = new IPEndPoint(IPAddress.Parse("234.5.6.7"), 7788);
    ReceiveClient = new UdpClient(7788);
    ReceiveClient.JoinMulticastGroup(IPAddress.Parse("234.5.6.7"));
    ReceivePort = new IPEndPoint(IPAddress.Parse("234.5.6.7"), 7788);
    t = new Thread(new ThreadStart(RecvThread));
    t.IsBackground = true;
    t.Start();
}
private void Update()
{
    if (Input.GetKey(KeyCode.A))
    {
        i++;
        byte[] buf = Encoding.Default.GetBytes(i.ToString());
        Sendclient.Send(buf, buf.Length, SendPort);
    }
    textShow.text = msgNma;
}
void RecvThread()
{

    // IPEndPoint multicast = new IPEndPoint(IPAddress.Parse("234.5.6.7"), 7788);
    while (true)
    {
        byte[] buf = ReceiveClient.Receive(ref ReceivePort);
        string msg = Encoding.Default.GetString(buf);
        msgNma = "Yang" + msg;
        Debug.Log(msg);
    }

}
private void OnApplicationQuit()
{
    if (t != null)
    {
        t.Interrupt();
        t.Abort();

    }
    //最后关闭socket  
    if (Sendclient != null || ReceiveClient != null)
    {
        Sendclient.Close();
        ReceiveClient.Close();
    }
}
}

UDP的组播:服务器接受信息的端口必须和客户端接受信息的socket 端口一致。
问:一个Udp Server加入某个组播组,然后绑定某个端口,开始接收数据,能接收到哪些数据?

答:可以接收到发往这个组播组这个端口的数据,可以接收到发往这个端口的广播数据,可以接收到专门发往这个端口的单播数据。

问:(1)怎样知道自己周围组播的组的情况(D类IP地址被占用的情况)?(2)自己可否只是通过编程就建立一个组播组?(没有找到资料)

答:(1)还不知道。(2)(不太明白详细具体情况)。是可以的,一个Socket往一个固定的组播地址的端口发送数据,那么一个组播的组就建立起了,其余计算机可以加入此地址标示的组,接收信息。(当然,需要硬件软件协议支持。另外对此组播地址的值也有限制,组播地址也有类似于192.168.0.0网络地址的,只用于局域网,不路由的地址)

上一篇 下一篇

猜你喜欢

热点阅读