- 最后登录
- 2021-7-6
- 注册时间
- 2012-12-27
- 阅读权限
- 90
- 积分
- 76145
- 纳金币
- 53488
- 精华
- 316
|
许多在unity里使用过Socket传输网络数据的人,也许都遇到过,VS里好好能运行的代码,在Unity里就直接卡死,其实这是在socket accept时造成里阻塞,只要开启线程去accept就可以解决了- using UnityEngine;
- using System.Collections;
- using System.Net.Sockets;
- using System.Net;
- using System.Collections.Generic;
- using System.Threading;
- public class ServerSocket : MonoBehaviour {
- Socket tcpserver;
- static List<Client> clientList = new List<Client>();
- private string IP;
- // Use this for initialization
- void Start() {
- IP = GetLocalIp();
- print(IP);
- tcpServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
- tcpServer.Bind(new IPEndPoint(IPAddress.Parse("192.168.1.120"), 7788));
- tcpServer.Listen(100);
- }
- static string GetLocalIp() { //获取本机局域网IP
- string hostname = Dns.GetHostName();//得到本机名
- IPHostEntry localhost = Dns.GetHostByName(hostname);//方法已过期,只得到IPv4的地址
- //IPHostEntry localhost = Dns.GetHostEntry(hostname); //可获取IPV6地址
- IPAddress localaddr = localhost.AddressList[0];
- return localaddr.ToString();
- }
- // Update is called once per frame
- void Update() {
- if (tcpServer != null) {
- Thread thread = new Thread(t => {
- Socket clienttSocket = tcpServer.Accept();
- Client client = new Client(clienttSocket);//把与每个客户端的逻辑放到client的对象里
- clientList.Add(client);
- });
- }
- }
- }
复制代码 上面的Client是我声明了另一个类,用来存储客户端连接是的信息,- using UnityEngine;
- using System.Collections;
- using System.Net.Sockets;
- using System.Net;
- public class Client : MonoBehaviour {
- private Socket clientSocket;
- public Client(Socket s) {
- clientSocket = s;
- }
- }
- using引用了如下
- using System.Net.Sockets;
- using System.Net;
- using System.Collections.Generic;
- using System.Threading;
复制代码 |
|