I’m trying to use this sample code to communicate with a server:
using UnityEngine;
using System;
using System.IO;
using System.Collections;
using System.Net.Sockets;
using System.Net;
public class Client : MonoBehaviour {
public string server = "127.0.0.1";
public int port = 10000;
void Start() {
try {
TcpClient client = new TcpClient(server, port);
Debug.Log("Connected: " + client.Connected);
byte[] messageData = System.Text.Encoding.ASCII.GetBytes("Hello!");
NetworkStream stream = client.GetStream();
stream.Write(messageData, 0, messageData.Length);
//NOTE: The response portion is commented out because I need to do it
//with an AsyncCallback
byte[] responseData = new byte[256];
Int32 bytes = stream.Read(responseData, 0, responseData.Length);
string response = System.Text.Encoding.ASCII.GetString(responseData, 0, bytes);
Debug.Log(response);
}
catch(Exception e) {
Debug.Log(e.InnerException.Message);
}
}
}
…It works otherwise fine, but Unity freezes completely until answer from server arrives.
Is it possible to do somethig about this, so that Unity program would continue to run while waiting for answer from server?
There was something about using “AsyncCallback”, but I have no idea what that means in practice in this case… (I don’t have any previous experience about network programming.)
Code sample is copied from here:
http://answers.unity3d.com/questions/275291/issues-with-unity-and-net-sockets.html?sort=oldest