之前学习的客户端当然可以实现基本的功能,只是会出现卡顿的现象,用户的体验并不是很好,我们现在用异步实现这样的功能
具体完整的代码:
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; } }
异步包括了三部分的异步,连接异步,发送异步,接收异步,也都是通过委托方法实现的。
原文地址:https://www.cnblogs.com/Optimism/p/12249917.html
时间: 2024-10-14 02:14:07