客户端:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using UnityEngine;
public class ClientCore : MonoBehaviour {
public static ClientCore instance = null;
//建立的通讯
private TcpClient client;
//Stream流
private NetworkStream stream;
//连接是否处于活动中
private bool __connected = false;
public bool connected
{
get { return __connected; }
}
//接受队列
public Queue<string> recvQueue = new Queue<string>();
//发送队列
public Queue<string> sendQueue = new Queue<string>();
//缓存区大小
private int maxBufferSize = 4096;
//线程
public Thread clientThread = null;
//是否停止线程
private volatile bool stop = false;
//全局唯一性
private void Awake () {
if (instance != null)
{
Debug.Log("严重 : ClientCore已经存在!");
DestroyImmediate(gameObject);
}else
{
DontDestroyOnLoad(gameObject);
instance = this;
}
}
private void Start()
{
instance = this;
//stop = false;
//开启客户端主线程
clientThread = new Thread(new ThreadStart(StartClient));
clientThread.IsBackground = true; //设为后台线程,伴随主线程关闭而关闭
clientThread.Start();
}
//socket连接是否有效
bool IsOpen()
{
return !((client.Client.Poll(1000, SelectMode.SelectRead) && (client.Client.Available == 0)) || !client.Client.Connected);
}
//Client线程
void StartClient()
{
byte[] recvBuf = new byte[maxBufferSize];
while (!stop)
{
if (!__connected)
{
//尝试开启一个连接
TryConnect();
}
//检查发送队列
if (sendQueue.Count > 0 && __connected)
{
byte[] buffer = Encoding.UTF8.GetBytes(sendQueue.Dequeue());
stream.Write(buffer, 0, buffer.Length);
stream.Flush();
}
//检查流接受数据
if (stream.DataAvailable && __connected)
{
int bytesRead