gpt4 book ai didi

unity-game-engine - Unity TCP Server 挂起 Unity 场景

转载 作者:行者123 更新时间:2023-12-02 17:34:00 26 4
gpt4 key购买 nike

我正在尝试统一实现一个TCP服务器。我正在使用 unity pro 3.5,当我在场景中运行此代码时,unity 挂起,完全没有响应,直到我用任务管理器杀死它。

using UnityEngine;
using System.Collections;
using System.Net.Sockets;
using System.Net;
using System.Text;


public class Server : MonoBehaviour {

private IPAddress ipAd;
public string IP="127.0.0.1";
public int port = 8001;
private Socket s;

void Update ()
{

}

// Use this for initialization
void Awake () {
port = 8001;
ipAd = IPAddress.Parse(IP);
msg = "Listening at " + IP + ":" + port.ToString();
this.s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
this.s.Bind(new IPEndPoint(ipAd,port));
this.s.Listen(200);
while (true)
this.ReceiveMessage(this.s.Accept()); //hang if this line activated
}
private void ReceiveMessage(Socket socket)
{
byte[] tempbuffer = new byte[10000];
socket.Receive(tempbuffer);
rec.AssignFromByteArray(tempbuffer);
}
}

最佳答案

服务器应该在它自己的线程中运行,这样即使 tcp_Listener.AcceptSocket() 是一个阻塞调用,GameLoop 也可以继续。

using UnityEngine;
using System.Collections;
using System.Threading;
using System.Net;
using System.Net.Sockets;
using System.IO;

public class Server : MonoBehaviour {
private bool mRunning;
public static string msg = "";

public Thread mThread;
public TcpListener tcp_Listener = null;

void Awake() {
mRunning = true;
ThreadStart ts = new ThreadStart(Receive);
mThread = new Thread(ts);
mThread.Start();
print("Thread done...");
}

public void stopListening() {
mRunning = false;
}

void Receive() {
tcp_Listener = new TcpListener(IPAddress.Parse("127.0.0.1"), 8001);
tcp_Listener.Start();
print("Server Start");
while (mRunning)
{
// check if new connections are pending, if not, be nice and sleep 100ms
if (!tcp_Listener.Pending()){
Thread.Sleep(100);
}
else {
Socket ss = tcp_Listener.AcceptSocket();
BonePos rec = new BonePos();
byte[] tempbuffer = new byte[10000];
ss.Receive(tempbuffer); // received byte array from client
rec.AssignFromByteArray(tempbuffer); // my own datatype
}
}
}

void Update() {

}

void OnApplicationQuit() { // stop listening thread
stopListening();// wait for listening thread to terminate (max. 500ms)
mThread.Join(500);
}
}

参见Related answer from answers.unity3d.com

关于unity-game-engine - Unity TCP Server 挂起 Unity 场景,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13965633/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com