1
J'essaye d'implémenter un serveur TCP dans l'unité. J'utilise unity pro 3.5
et quand je cours ce code dans une scène, puis l'unité se bloque, aucune réponse du tout jusqu'à ce que je le tue avec le gestionnaire de tâches.Unity TCP Server Hang Unity scène
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);
}
}
'mRunning' devrait être volatile. La variable est définie par le thread Unity et lue à partir du thread de réception. L'accès doit donc être synchronisé. – Vertex