C# UDP to数据

using LitJson;
//引入库
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using UnityEngine;

public class UdpClient : MonoBehaviour
{
    public delegate void logMessagaeBarScanResultDelegat(string message);
    public static logMessagaeBarScanResultDelegat logMBSRD;


    private static UdpClient instance;

    private UdpClient()
    {
        
    }

    public static  UdpClient Instance()
    {
        if (instance == null)
            instance = new UdpClient();
        return instance;
    }

    //以下默认都是私有的成员
    string AddressIP;//获取ip
    Socket socket; //目标socket
    EndPoint serverEnd; //服务端
    IPEndPoint ipEnd; //服务端端口
    IPEndPoint ipSocketEnd;//蓝牙服务端口
    IPEndPoint ipSocketPC; //点云服务端口
    string recvStr; //接收的字符串
    string sendStr; //发送的字符串
    byte[] recvData = new byte[4096]; //接收的数据,必须为字节
    byte[] sendData = new byte[4096]; //发送的数据,必须为字节
    int recvLen; //接收的数据长度
    Thread connectThread; //连接线程
    //初始化
    void InitSocket()
    {
        //定义连接的服务器ip和端口,可以是本机ip,局域网,互联网  ( ip地址和端口号 后端提供)
       // ipSocketEnd = new IPEndPoint(IPAddress.Parse("192.168.x.x"), 9981);

        ipSocketPC = new IPEndPoint(IPAddress.Parse("192.168.x.x"), 9981);
        ipSocketEnd = new IPEndPoint(IPAddress.Parse("192.168.x.x"), 9981);
        ipEnd = new IPEndPoint(IPAddress.Parse(AddressIP), 9981);
       // ipEnd = new IPEndPoint(IPAddress.Parse("192.168.220.178"), 9981);
        //定义套接字类型,在主线程中定义
        socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
        socket.Bind(ipEnd);
        //定义服务端
        IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
        serverEnd = (EndPoint)sender;

        //建立初始连接,这句非常重要,第一次连接初始化了serverEnd后面才能收到消息
        SocketSend("hello");

        //开启一个线程连接,必须的,否则主线程卡死
        connectThread = new Thread(new ThreadStart(SocketReceive));
        connectThread.Start();
    }

    void SocketSend(string sendStr)
    {
        //清空发送缓存
        sendData = new byte[4096];
        //数据类型转换
        sendData = Encoding.ASCII.GetBytes(sendStr);
        //发送给指定服务端
        socket.SendTo(sendData, sendData.Length, SocketFlags.None, ipSocketEnd);
        
        
    }

    void SocketSendPointCloud(string sendStr)
    {
        //清空发送缓存
        sendData = new byte[4096];
        //数据类型转换
        sendData = Encoding.ASCII.GetBytes(sendStr);
        //发送给指定服务端
        socket.SendTo(sendData , ipSocketPC);
        

    }

    //服务器接收
    void SocketReceive()
    {
        //进入接收循环
        while (true)
        {
            //对data清零
            recvData = new byte[4096];
            Debug.Log("1111111111111");
            //获取客户端,获取服务端端数据,用引用给服务端赋值,实际上服务端已经定义好并不需要赋值
            recvLen = socket.ReceiveFrom(recvData, ref serverEnd);
            Debug.Log("22222222222222"  + recvLen);
            //Debug.LogError("message from: " + serverEnd.ToString()); //打印服务端信息
            //输出接收到的数据
            recvStr = Encoding.ASCII.GetString(recvData, 0, recvLen);
            //print(recvStr+"消息");
            // Debug.Log(recvStr + "Idear");

           // TestJsonManage.state = true;
            TestJsonManage.result = recvStr.Trim();

            Debug.Log(TestJsonManage.state + "          " +"    "+ logMBSRD);

            // 当前连接 只需要传输一次数据 传输完成后关闭
           
           
        }
    }

    //连接关闭
    void SocketQuit()
    {
        //关闭线程
        if (connectThread != null)
        {
            connectThread.Interrupt();
            connectThread.Abort();
        }
        //最后关闭socket
        if (socket != null)
            socket.Close();
    }

    // Use this for initialization
    void Start()
    {

        ///获取本地的IP地址
        for (int i = 0; i < Dns.GetHostEntry(Dns.GetHostName()).AddressList.Length; i++)
        {
            if (Dns.GetHostEntry(Dns.GetHostName()).AddressList[i].AddressFamily.ToString() == "InterNetwork")
            {
                AddressIP = Dns.GetHostEntry(Dns.GetHostName()).AddressList[i].ToString();
            }
        }
        InitSocket(); //在这里初始化
        SendIpToBluetooth();//发送targeId,端口号
    }

    // Update is called once per frame
    void Update()
    {
    }

    public void SendIpToBluetooth()
    {
// 根据要传输的结构 自己创建类 SendNetConnectProtocol sendNet = new SendNetConnectProtocol(); sendNet.Tagid = DeviceSN.GetInstance().SendSerialBy16(); sendNet.Port = 9981; string jsonData = JsonMapper.ToJson(sendNet); Debug.Log(jsonData); SocketSend(jsonData); } //reporter: '606bee3edfda85745b71348d', //sn: '3ewqeq2e2qewe', //cmd: 'insertPositionRecord', //positionTs: '1617690133', //project: '6067d03db492a38dfe6e2265', //position: '{"x":1.3,"y":3.3,"z":1.2}', //positionType: 'PointCloud', public void SendIpToPointCloud(Vector3 pos, string PointionTs) {
// 根据传输结构 自己创建对应结构的类 SendNetConnectPointCloud sendNet = new SendNetConnectPointCloud(); sendNet.reporter = "606bee3edfda85745b71348d"; sendNet.sn = DeviceSN.GetInstance().SendSerialBy16(); sendNet.cmd = "insertPositionRecord"; sendNet.positionTs = PointionTs; sendNet.project = "6067d03db492a38dfe6e2265"; sendNet.position.x = pos.x; sendNet.position.y = pos.y; sendNet.position.z = pos.z; sendNet.positionType = "PointCloud"; string jsonData = JsonMapper.ToJson(sendNet); Debug.Log(jsonData); SocketSendPointCloud(jsonData); } void OnApplicationQuit() { SocketQuit(); } }

  

posted @ 2021-04-08 16:37  D个人笔记  阅读(34)  评论(0编辑  收藏  举报