unity UDP

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Text;
using System.IO;
using System;

public class oscnet : MonoBehaviour {

    public Socket MySocket;
    public string IpAdree= "127.0.0.1";
    public int port=7878;
    

    Thread connectThread;
	
	void Start () {

        MySocket = new Socket(AddressFamily.InterNetwork,SocketType.Dgram,ProtocolType.Udp);

        MySocket.Bind(new IPEndPoint(IPAddress.Parse(IpAdree), port));

     
        connectThread = new Thread(new ThreadStart(ReciveMsg));
        connectThread.Start();



    }




    public void ReciveMsg()
    {
        Debug.Log("开始线程了~");
        while (true)
        {

            EndPoint endPoint = new IPEndPoint(IPAddress.Any, 0);
            byte[] data = new byte[1024];
            int count = MySocket.ReceiveFrom(data, ref endPoint);

    

   
           string msg = System.Text.Encoding.UTF8.GetString(data, 0, count);
            Debug.Log("接收到:"+ msg);

        }

    }

	
	void Update () {
		
	}

  


    private void OnDestroy()
    {
        Debug.Log("关闭线程了");
        if (connectThread != null)
        {
            connectThread.Interrupt();
            connectThread.Abort();
        }
        //最后关闭socket
        if (MySocket != null)
            MySocket.Close();
    }


 



}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值