首页 学习日记正文

Unity异步网络通信

阿沐 学习日记 2020-05-20 1439 1 unity

Unity异步网络通信

image.png

客户端:

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

public class Echo : MonoBehaviour {

    Socket socket;

    public InputField inputField;
    public Text text;

    //接收缓冲区
    public byte[] readBuff = new byte[1024];
    string recvStr = "";

    void Start()
    {
        this.transform.Find("BtnConnect").GetComponent<Button>().onClick.AddListener(Connect);
        this.transform.Find("BtnSend").GetComponent<Button>().onClick.AddListener(Send);
        inputField = this.transform.Find("InputField").GetComponent<InputField>();
        text = this.transform.Find("Text").GetComponent<Text>();
    }

    void Update()
    {
        text.text = recvStr;
    }

    public void Connect()
    {
        //创建Socket
        socket = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
        //连接服务器【ip+端口】
        //socket.Connect("127.0.0.1",8888);

        //异步连接服务端
        socket.BeginConnect("127.0.0.1",8888,ConnectCallBack,socket);
    }

    //连接服务端成功的回调函数
    private void ConnectCallBack(IAsyncResult ar)
    {
        try
        {
            //获取socket对象
            Socket sok = (Socket)ar.AsyncState;
            //完成连接
            sok.EndConnect(ar);
            print("Socket 连接成功!");
            //开始接收信息
            socket.BeginReceive(readBuff,0,1024,0,ReceiveCallBack,socket);
        }
        catch(SocketException ex)
        {
            print("Socket 连接失败! "+ex.ToString());
        }
    }

    //开始接收信息的回调函数
    private void ReceiveCallBack(IAsyncResult ar)
    {
        try
        {
            //获取socket通道
            Socket sok = (Socket)ar.AsyncState;
            //计算服务端发送的信息长度
            int count = sok.EndReceive(ar);
            //将字节数组转换成字符串
            recvStr = System.Text.Encoding.Default.GetString(readBuff,0,count);
            //继续接收信息
            socket.BeginReceive(readBuff,0,1024,0,ReceiveCallBack,socket);
        }
        catch (SocketException ex)
        {
            print("Socket 接收失败!"+ex.ToString());
        }
    }

    public void Send()
    {
        //获取文本内容
        string sendStr = inputField.text;
        //将字符串内容转换成字节数组
        byte[] sendBytes = System.Text.Encoding.Default.GetBytes(sendStr);
        //像服务端发送消息
        //socket.Send(sendBytes);
        //异步发送消息
        socket.BeginSend(sendBytes, 0, sendBytes.Length, 0, SendCallBack, socket);
    }

    //发送数据的回调函数
    private void SendCallBack(IAsyncResult ar)
    {
        try
        {
            //获取socket通道
            Socket sok = (Socket)ar.AsyncState;
            //EndSend表示发送完全,返回数据长度
            int count=socket.EndSend(ar);
            print("Socket 发送数据成功!"+count);
        }
        catch (SocketException ex)
        {
            print("Socket 发送失败!"+ex.ToString());
        }
    }
}


image.png

服务端:

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

namespace NetStudyServer
{
    class ClientState
    {
        public Socket socket;
        public byte[] readBuff=new byte[1024];
    }


    class Program
    {
        public static Socket listenfd;
        public static Dictionary<Socket, ClientState> clientDict = new Dictionary<Socket, ClientState>();

        static void Main(string[] args)
        {
            Console.WriteLine("这里是服务端");
            //创建Socket
            listenfd = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);

            //绑定IP和端口
            IPAddress ipAddr = IPAddress.Parse("127.0.0.1");
            IPEndPoint ipEp = new IPEndPoint(ipAddr,8888);
            listenfd.Bind(ipEp);

            //开启监听
            listenfd.Listen(0);
            Console.WriteLine("服务端开启成功!");

            //开始接收客户端消息
            listenfd.BeginAccept(AcceptCallBack,listenfd);
            //等待
            Console.ReadKey();
        }

        //服务端接收消息的回调函数
        private static void AcceptCallBack(IAsyncResult ar)
        {
            try
            {
                //服务端的socket
                Socket listenfd = (Socket)ar.AsyncState;
                //获取客户端的socket通道
                Socket clientSok = listenfd.EndAccept(ar);

                //创建client列表,添加至字典
                ClientState state = new ClientState();
                state.socket = clientSok;
                clientDict.Add(clientSok, state);
                //开始接收客户端消息
                clientSok.BeginReceive(state.readBuff,0,1024,0,ReceiveCallBack,state);
                //继续接收
                listenfd.BeginAccept(AcceptCallBack, listenfd);
            }
            catch (SocketException ex)
            {
                Console.WriteLine("Socket 接收失败!"+ex.ToString());
            }
        }

        //开始接收客户端消息的回调函数
        private static void ReceiveCallBack(IAsyncResult ar)
        {
            try
            {
                ClientState state = (ClientState)ar.AsyncState;
                Socket clientfd = state.socket;
                int count = clientfd.EndReceive(ar);

                if (count == 0)
                {
                    clientfd.Close();
                    clientDict.Remove(clientfd);
                    Console.WriteLine("Socket 关闭连接");
                    return;
                }
                string recvStr = System.Text.Encoding.Default.GetString(state.readBuff,0,count);
                byte[] sendBytes = System.Text.Encoding.Default.GetBytes("echo"+recvStr);
                clientfd.Send(sendBytes);
                clientfd.BeginReceive(state.readBuff,0,1024,0,ReceiveCallBack,state);
            }
            catch (SocketException ex)
            {
                Console.WriteLine("Socket 接收失败!"+ex.ToString());
            }
        }
    }
}


打赏

评论

精彩评论
Music