zoukankan      html  css  js  c++  java
  • Unity Socket UDP

    using System.Collections;
    using System.Collections.Generic;
    using System.Net.Sockets;
    using System.Net;
    using System.Threading;
    using System.Text;
    
    
    public class SocketUDPServer
    {
        private string ip = "127.0.0.1";
        private int port = 5690;
        private Socket socket;
        private static SocketUDPServer socketServer;
        public List<string> listMessage = new List<string>();
    
        public static SocketUDPServer getInstance()
        {
            if (socketServer == null)
            {
                socketServer = new SocketUDPServer();
                socketServer.Init();
            }
            return socketServer;
        }
    
        private void Init()
        {
            IPAddress ipAddress = IPAddress.Parse(ip);
            IPEndPoint IPE = new IPEndPoint(ipAddress,port);
            //Udp搭配SocketType.Dgram   Tcp搭配SocketType.Stream
            socket=new Socket(AddressFamily.InterNetwork,SocketType.Dgram,ProtocolType.Udp);
            socket.Bind(IPE);
            Thread threadReceive = new Thread(new ThreadStart(ReceiveMessage));
            threadReceive.Start();
        }
        private void ReceiveMessage()
        {
            while (true)
            {
                byte[] buff = new byte[1024];
                int iBytes = socket.Receive(buff, SocketFlags.None);
                if (iBytes <= 0)
                    break;
                string strGetMessage = Encoding.ASCII.GetString(buff, 0, iBytes);
                listMessage.Add(strGetMessage);
            }
        }
        public void  Close()
        {
            if(socket!=null)
                socket.Close();
        }
       
    
    }
    

  • 相关阅读:
    [ZZ]C++中,引用和指针的区别
    面试总结之JAVA
    LeetCode 347. Top K Frequent Elements
    LeetCode 342. Power of Four
    腾讯//删除链表中的节点
    腾讯//删除链表中的节点
    腾讯//相交链表
    腾讯//相交链表
    腾讯//环形链表 II
    腾讯//环形链表 II
  • 原文地址:https://www.cnblogs.com/liang123/p/6325913.html
Copyright © 2011-2022 走看看