【Unity&C#】运行在主线程的Socket

本文介绍如何在Unity中使用协程实现单线程Socket通信,避免多线程带来的线程安全问题。通过封装C# Socket并设置为非阻塞模式,结合Unity的协程功能,简化了Socket的接收数据过程。示例代码中展示了如何启动NetworkManager,创建消息处理类,并进行消息注册和接收。
摘要由CSDN通过智能技术生成

通常的Socket都是通过多线程的方式来实现的,多线程需要确保线程安全,而且代码量也会相对多一些,由于之前已经实现了Unity的协程功能,现在就可以通过协程来实现单线程的Socket了。
首先,封装一下C#的Socket。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;
using FirBase;

namespace NxNetwork
{
    public class NxSocket
    {
        private Socket _socket;

        public NxSocket()
        {
            _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        }

        public bool Connect(string ip, int port)
        {
            return Connect(new IPEndPoint(IPAddress.Parse(ip), port));
        }

        public bool Connect(IPEndPoint ipPoint)
        {
            bool connected = false;
            try
            {
                FirLog.v(this, "连接服务器:" + ipPoint.Address.ToString());
                _socket.NoDelay = true;
                _socket.Connect(ipPoint);
                _socket.Blocking = false;
                connected = true;
            }
            catch(Exception ex)
            {
                FirLog.v(this, "连接出现异常:" + ex.Message);
            }
            return connected;
        }

        public bool Disconnect()
        {
            bool success = false;
            try
            {
                _socket.Shutdown(SocketShutdown.Both);
                _socket.Close();
                success = true;
            }
            ca
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值