Socket通信示例——异步通信

该博客详细介绍了如何在Unity环境下使用Socket进行异步通信。内容包括服务器端的Conn类和服务器类的实现,以及客户端的控制方法,为Unity网络编程提供了实践指导。
摘要由CSDN通过智能技术生成

服务器端:

Conn类

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

using System.Net;
using System.Net.Sockets;

public class Conn 
{
   
    public const int BUFFER_SIZE = 1024;

    public Socket socket;

    public byte[] readBuff = new byte[BUFFER_SIZE];

    public int buffCount = 0;  //处理分包和粘包

    public bool isUse;


    /// <summary>
    /// 初始化
    /// </summary>
    /// <param name="Scok"></param>
    public void Init(Socket Scok)
    {
   
        socket = Scok;
        isUse = true;
        buffCount = 0;
    }

    //返回剩余buff缓存
    public int BuffRemain()
    {
   
        return BUFFER_SIZE - buffCount;
    }

    //客户端地址
    public string GetAdress()
    {
   
        if (!isUse)
            return "无法获取当前用户地址";
        return socket.RemoteEndPoint.ToString();
    }

    public void Close()
    {
   
        if (!isUse)
            return;

        socket.Close();
        isUse = false;

    }

}

服务器类

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

public class Serv
{
   
    public Socket listenfd;

    public Conn[] conns;

    public int maxCon = 30;

    public int NewIndex()
    {
   
        if (conns == null)
            return -1;
        for (int i = 
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值