网络异步实现客户端

Posted optimism

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了网络异步实现客户端相关的知识,希望对你有一定的参考价值。

 

之前学习的客户端当然可以实现基本的功能,只是会出现卡顿的现象,用户的体验并不是很好,我们现在用异步实现这样的功能

 

具体完整的代码:

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


public class Echo : MonoBehaviour
{
    //定义套接字
    Socket socket;

    //定义UGUI
    public InputField inputField;
    public Text text;

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

    // 点击连接按钮
    public void Connection()
    {
        //Socket
        socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

        //Connect
        //socket.Connect("127.0.0.1", 8888);

        //Connect
        socket.BeginConnect("127.0.0.1", 8888, ConnectCallback, socket);
    }

    //Connect回调
    public void ConnectCallback(IAsyncResult ar)
    {
        try
        {
            Socket socket = (Socket)ar.AsyncState;
            socket.EndConnect(ar);
            Debug.Log("Socket Connect Succ");
            socket.BeginReceive(readBuff, 0, 1024, 0, ReceiveCallback, socket);

        }
        catch (SocketException ex)
        {
            Debug.Log("Socket Connect fail" + ex.ToString());
        }
    }

    //Receive回调
    public void ReceiveCallback(IAsyncResult ar)
    {
        try
        {
            Socket socket = (Socket)ar.AsyncState;
            int count = socket.EndReceive(ar);
            recvStr = System.Text.Encoding.Default.GetString(readBuff, 0, count);

            socket.BeginReceive(readBuff, 0, 1024, 0, ReceiveCallback, socket);
        }
        catch (SocketException ex)
        {
            Debug.Log("Socket Receive fail" + ex.ToString());
        }
    }

    // 点击发送按钮
    public void Send()
    {
        //Send 
        string sendStr = inputField.text;
        byte[] sendBytes = System.Text.Encoding.Default.GetBytes(sendStr);
        socket.BeginSend(sendBytes, 0, sendBytes.Length, 0, SendCallback, socket);
    }

    //Send回调
    public void SendCallback(IAsyncResult ar)
    {
        try
        {
            Socket socket = (Socket)ar.AsyncState;
            int count = socket.EndSend(ar);
            Debug.Log("Socket Send succ" + count);
        }
        catch (SocketException ex)
        {
            Debug.Log("Socket Send fail" + ex.ToString());
        }
    }

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

}

 

异步包括了三部分的异步,连接异步,发送异步,接收异步,也都是通过委托方法实现的。

 

以上是关于网络异步实现客户端的主要内容,如果未能解决你的问题,请参考以下文章

Voovan 是一个高性能异步网络框架和 HTTP(Java)

一种基于Qt的可伸缩的全异步C/S架构server实现 网络传输

如何延迟或异步此 WordPress javascript 片段以最后加载以加快页面加载时间?

用python怎样实现异步redis客户端

AsyncTask实现网络图片的异步加载

golang代码片段(摘抄)