TcpClient Socket通信、简单消息传递---(Unity自学笔记)

客户端:

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 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值