将我的评论扩展为更具描述性和具体性,我的建议是创建一个简单的Thread,作为与您的服务器的通信管理器。
首先你必须实现 this class 来调用 Unity 的 UI 线程上的方法。
当你实现这个时,只需创建一个类:
public class CommunicationManager
{
static readonly object syncRoot = new object();
static CommunicationManager _Instance;
public static CommunicationManager Instance
{
get
{
if ( _Instance == null )
{
lock ( syncRoot )
{
if ( _Instance == null )
{
_Instance = new CommunicationManager();
}
}
}
return _Instance;
}
}
volatile bool working = false;
Queue<Message> _messages;
private CommunicationManager()
{
_messages = new Queue<Message>();
InitializeCommunication();
}
void InitializeCommunication()
{
Thread t = new Thread(CommunicationLoop);
t.Start();
}
void CommunicationLoop()
{
Socket s = null;
try
{
Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
s.Connect(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 1337));
working = true;
}
catch(Exception ex)
{
working = false;
}
while ( working )
{
lock ( syncRoot )
{
while ( _messages.Count > 0 )
{
Message message = _messages.Dequeue();
MessageResult result = message.Process(s);
result.Notify();
}
}
Thread.Sleep(100);
}
}
public void EnqueueMessage(Message message)
{
lock ( syncRoot )
{
_messages.Enqueue( message );
}
}
}
现在你必须创建 Message 和 MessageResult 对象:
public class Message
{
const string REQUEST_SCHEME = "{0} {1} HTTP/1.1\r\nHost: {hostname}\r\nContent-Length: 0\r\n\r\n";
string request;
Action<MessageResult> whenCompleted;
public Message(string requestUri, string requestType, Action<MessageResult> whenCompleted)
{
request = string.Format(REQUEST_SCHEME, requestType, requestUri);
this.whenCompleted = whenCompleted;
}
public MessageResult Process(Socket s)
{
IPEndPoint endPoint = (IPEndPoint)s.RemoteEndPoint;
IPAddress ipAddress = endPoint.Address;
request = request.Replace("{hostname}", ipAddress.ToString());
s.Send(Encoding.UTF8.GetBytes(request));
// receive header here which should look somewhat like this :
/*
HTTP/1.1 <status>
Date: <date>
<some additional info>
Accept-Ranges: bytes
Content-Length: <CONTENT_LENGTH>
<some additional info>
Content-Type: <content mime type>
*/
// when you receive this all that matters is <CONTENT_LENGTH>
int contentLength = <CONTENT_LENGTH>;
byte[] msgBuffer = new byte[contentLength];
if (s.Receive(msgBuffer) != contentLength )
{
return null;
}
return new MessageResult(msgBuffer, whenCompleted);
}
}
最后创建 MessageResult 对象:
public class MessageResult
{
Action<MessageResult> notifier;
byte[] messageBuffer;
public MessageResult(byte[] message, Action<MessageResult> notifier)
{
notifier = notifier;
messageBuffer = message;
}
public void Notify()
{
UnityThread.executeInUpdate(() =>
{
notifier(this);
});
}
}
此方法将在您的主应用程序之外运行,因此不会产生任何冻结等。
要使用它,你可以这样调用:
Message message = new Message("/index.html", "GET", IndexDownloaded);
CommunicationManager.Instance.EnqueueMessage(message);
// ...
public void IndexDownloaded(MessageResult result)
{
// result available here
}
有关更多信息,请阅读this wikipedia 关于 HTTP 的文章。