纳金网

标题: Unity Socket Accept卡死的问题 [打印本页]

作者: 烟雨    时间: 2015-12-19 06:57
标题: Unity Socket Accept卡死的问题

许多在unity里使用过Socket传输网络数据的人,也许都遇到过,VS里好好能运行的代码,在Unity里就直接卡死,其实这是在socket accept时造成里阻塞,只要开启线程去accept就可以解决了
  1. using UnityEngine;
  2. using System.Collections;
  3. using System.Net.Sockets;
  4. using System.Net;
  5. using System.Collections.Generic;
  6. using System.Threading;

  7. public class ServerSocket : MonoBehaviour {
  8.     Socket tcpServer;
  9.     static List<Client> clientList = new List<Client>();
  10.     private string IP;
  11.     // Use this for initialization
  12.     void Start() {
  13.         IP = GetLocalIp();
  14.         print(IP);
  15.         tcpServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  16.         tcpServer.Bind(new IPEndPoint(IPAddress.Parse("192.168.1.120"), 7788));

  17.         tcpServer.Listen(100);
  18.     }
  19.     static string GetLocalIp() {  //获取本机局域网IP
  20.         string hostname = Dns.GetHostName();//得到本机名   
  21.         IPHostEntry localhost = Dns.GetHostByName(hostname);//方法已过期,只得到IPv4的地址   
  22.         //IPHostEntry localhost = Dns.GetHostEntry(hostname);  //可获取IPV6地址
  23.         IPAddress localaddr = localhost.AddressList[0];
  24.         return localaddr.ToString();
  25.     }
  26.     // Update is called once per frame
  27.     void Update() {
  28.         if (tcpServer != null) {
  29.             Thread thread = new Thread(t => {
  30.                 Socket clienttSocket = tcpServer.Accept();
  31.                 Client client = new Client(clienttSocket);//把与每个客户端的逻辑放到client的对象里
  32.                 clientList.Add(client);
  33.             });
  34.         }
  35.     }
  36. }
复制代码
上面的Client是我声明了另一个类,用来存储客户端连接是的信息,
  1. using UnityEngine;
  2. using System.Collections;
  3. using System.Net.Sockets;
  4. using System.Net;

  5. public class Client : MonoBehaviour {
  6.     private Socket clientSocket;

  7.     public Client(Socket s) {
  8.         clientSocket = s;
  9.     }
  10. }

  11. using引用了如下
  12. using System.Net.Sockets;
  13. using System.Net;
  14. using System.Collections.Generic;
  15. using System.Threading;
复制代码





欢迎光临 纳金网 (http://rs.narkii.com/club/) Powered by Discuz! X2.5