using System.Collections; using System.Collections.Generic; using UnityEngine; using System.Net; using System.Net.Sockets; using System.Text; using System;
publicclassclientTest : MonoBehaviour { Socket socket=new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //设置端口 int port = 12345;
byte[] data = newbyte[1024]; voidStart() { socket.Connect("localhost", port); Debug.Log("客户端启动!");
}
// Update is called once per frame voidUpdate() { //检查是否有可用的数据 if (socket.Available > 0) { //接收服务器返回的数据 //Receive是阻断试的,当没有新的数据到达将会卡在update方法中 int received = socket.Receive(data); string message = Encoding.UTF8.GetString(data, 0, received); Array.Clear(data, 0, received); Debug.Log(message); } } //类似析构函数,当组件销毁时调用 voidOnDestroy() { //关闭socket socket.Close(); } }
Copyright:
Copyright is owned by the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source.