Unity Socket TCP

20 篇文章 2 订阅

Server:

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 Server : MonoBehaviour
{
    #region TCP

    private Socket _serverSocket;
    private bool _isRunThread = true;

    private List<SocketState> _socketStates;

    private void Start()
    {
        Init();
    }

    private void Update()
    {
        if (_socketStates.Count > 0)
        {
            foreach (SocketState state in _socketStates)
            {
                state.BeginReceive();
            }
        }
    }

    private void Init()
    {
        _socketStates = new List<SocketState>();
        IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Any, 18010);
        _serverSocket = new Socket(ipEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
        _serverSocket.Bind(ipEndPoint);
        _serverSocket.Listen(10);

        Thread thread = new Thread(ListenRecv);
        thread.Start();
    }

    /// <summary>
    /// 接收数据
    /// </summary>
    private void ListenRecv()
    {
        while (_isRunThread)
        {
            try
            {
                _serverSocket.BeginAccept(AsyncCallBack, _serverSocket);
            }
            catch (Exception ex)
            {
                
            }
        }
        Thread.Sleep(1000);
    }

    /// <summary>
    /// 异步得到数据
    /// </summary>
    /// <param name="ar">返回的数据就是socket</param>
    private void AsyncCallBack (IAsyncResult ar)
    {
        Socket listnSocket = (Socket) ar.AsyncState;

        //堵塞式
        Socket clientSocket = listnSocket.EndAccept(ar);
        _socketStates.Add(new SocketState(clientSocket));
    }

    #endregion

    private void OnDestroy()
    {
        _serverSocket.Shutdown(SocketShutdown.Both);
        _serverSocket.Close();
    }

}

/// <summary>
/// 客户端的连接
/// </summary>
public class SocketState
{
    private Socket _clientSocket;
    private byte[] _bufferBytes;

    public SocketState(Socket clientSocket)
    {
        _clientSocket = clientSocket;
        _bufferBytes = new byte[1024];
    }

    #region BeginReceive

    /// <summary>
    /// 异步接收数据
    /// </summary>
    public void BeginReceive()
    {
        _clientSocket.BeginReceive(_bufferBytes, 0, 1024, SocketFlags.None, BeginReceiveCallback, this);
    }

    private void BeginReceiveCallback(IAsyncResult ar)
    {
        int lenth = _clientSocket.EndReceive(ar);

        string str = Encoding.Default.GetString(_bufferBytes, 0, lenth);
        Debug.Log("server receive ---->" + str);

        BeginSend(str);
    }

    #endregion

    #region Send

    public void BeginSend(string msg)
    {
        byte[] buffer = Encoding.Default.GetBytes(msg);

        _clientSocket.BeginSend(buffer, 0, buffer.Length, SocketFlags.None, BeginSendCallback, this);
    }

    private void BeginSendCallback(IAsyncResult ar)
    {
        int lenth = _clientSocket.EndSend(ar);
        Debug.Log("send lenth --->" + lenth);
    }

    #endregion

}


client:

using System;
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
using UnityEngine;

public class Client : MonoBehaviour
{
    #region TCP

    private Socket _clientSocket;
    private byte[] _bufferBytes;

    private SocketBuffer _socketBuffer;

    private void Start()
    {
        _socketBuffer = new SocketBuffer(6, CallBackRecvOver);
        Init();
    }

    private void CallBackRecvOver(byte[] addData)
    {
        //接收到整个消息
    }

    private void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            BeginSend("123456789");
        }
        BeginReceive();
    }

    private void Init()
    {
        _bufferBytes = new byte[1024];

        IPAddress address = IPAddress.Parse("127.0.0.1");
        IPEndPoint point = new IPEndPoint(address, 18010);
        _clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

        _clientSocket.BeginConnect(point, BeginConnectCallback, _clientSocket);
    }

    /// <summary>
    /// 开始异步连接
    /// </summary>
    /// <param name="ar"></param>
    private void BeginConnectCallback(IAsyncResult ar)
    {
        _clientSocket.EndConnect(ar);
        Debug.Log("connect server is finish!!!");
    }

    #region BeginReceive

    /// <summary>
    /// 异步接收数据
    /// </summary>
    public void BeginReceive()
    {
        _clientSocket.BeginReceive(_bufferBytes, 0, 1024, SocketFlags.None, BeginReceiveCallback, this);
    }

    private void BeginReceiveCallback(IAsyncResult ar)
    {
        int lenth = _clientSocket.EndReceive(ar);

        _socketBuffer.RecvByte(_bufferBytes, lenth);

        //string str = Encoding.Default.GetString(_bufferBytes, 0, lenth);
        //Debug.Log("收到服务器数据 ---->" + str);
    }

    #endregion

    #region Send

    public void BeginSend(string msg)
    {
        byte[] buffer = Encoding.Default.GetBytes(msg);

        _clientSocket.BeginSend(buffer, 0, buffer.Length, SocketFlags.None, BeginSendCallback, this);
    }

    private void BeginSendCallback(IAsyncResult ar)
    {
        int lenth = _clientSocket.EndSend(ar);
        Debug.Log("发送到服务器数据 --->" + lenth);
    }

    #endregion
    private void OnDestroy()
    {
        _clientSocket.Shutdown(SocketShutdown.Both);
        _clientSocket.Close();
    }

    #endregion
}



评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值