using System;using System.Collections;using System.Collections.Generic;using System.Net.Sockets;using UnityEngine;using UnityEngine.UI;public class Echo : MonoBehaviour{ //定义套接字 Socket socket; //UGUI public InputField inputField; public Text text; //接受缓冲区 byte[] readBuff = new byte[1024]; string recvStr = ""; /// <summary> /// 点击连接按钮 /// </summary> public void Connection() { //Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //Connect socket.BeginConnect("127.0.0.1", 8888, ConnectCallback, socket); } /// <summary> /// Connect回调 /// </summary> /// <param name="ar"></param> 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()); } } /// <summary> /// Receive回调 /// </summary> /// <param name="ar"></param> 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 (Exception ex) { Debug.Log("Socket Receive fail" + ex.ToString()); } } /// <summary> /// 点击发送按钮 /// </summary> 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); //后面就不需要Receive了 } //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; }}