如果socket的recive放在update里,当这个比较卡的时候,就会丢失掉部分数据。最好是单独开一个线程来处理。
using UnityEngine;
using System.Collections;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Collections.Generic;
public class test : MonoBehaviour {
// Use this for initialization
void Start () {
ThreadStart ts = new ThreadStart(test.ThreadWork);
Thread tr = new Thread(ts);
//tr.Priority = System.Threading.ThreadPriority.Lowest;
tr.Start();
}
public static List<string> send = new List<string>();
public static List<string> recv = new List<string>();
public static Mutex smutex = new Mutex();
public static Mutex rmutex = new Mutex();
static Socket soc;
public static void ThreadWork()
{
soc = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
soc.Connect("localhost", 6000);
soc.Blocking = false;
while (true)
{
if (soc.Connected)
{
//while (send.Count > 0)
//{
// smutex.WaitOne();
// string st = send[0];
// send.RemoveAt(0);
// smutex.ReleaseMutex();
// soc.Send(Encoding.UTF8.GetBytes(st));
//}
while (soc.Available > 1)
{
byte[] buff = new byte[1024];
soc.Receive(buff);
string rst = Encoding.UTF8.GetString(buff);
rmutex.WaitOne();
recv.Add(rst);
rmutex.ReleaseMutex();
}
}
else
{
soc.Connect("localhost", 6000);
Thread.Sleep(1000);
}
}
}
// Update is called once per frame
void Update () {
if (send.Count < 1)
{
smutex.WaitOne();
send.Add("zhao");
smutex.ReleaseMutex();
}
while (recv.Count > 0)
{
rmutex.WaitOne();
string rt = recv[0];
recv.RemoveAt(0);
rmutex.ReleaseMutex();
Debug.Log(rt);
}
//while (soc != null && soc.Available > 1)
//{
// byte[] buff = new byte[1024];
// soc.Receive(buff);
// string rst = Encoding.UTF8.GetString(buff);
// Debug.Log(rst);
//}
}
}