客户端实现示例
一、最基础的客户端实现
实现的基本步骤: 1. 创建套接字Socket 2. 用Connect方法与服务器相连接 3. 使用Send和Receive相关方法收发数据 4. 用Shutdown方法释放链接 5. 关闭套接字
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| Socket _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint ipPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8080); try { _socket.Connect(ipPoint); } catch (SocketException e) { if (e.ErrorCode == 10061) { print("服务器拒绝链接"); } else { print("服务器链接失败,错误代码是:" + e.ErrorCode); } }
byte[] receiveBytes = new byte[1024]; int receiveNum = _socket.Receive(receiveBytes); print("收到服务端发来的消息:"+Encoding.UTF8.GetString(receiveBytes, 0, receiveNum));
_socket.Send(Encoding.UTF8.GetBytes("你好,这里是测试客户端一号"));
_socket.Shutdown(SocketShutdown.Both);
_socket.Close();
|
二、实现简单的与服务端通信
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
| public class NetMgr : MonoBehaviour { private static NetMgr instance; public static NetMgr Instance => instance; private Queue<string> sendMsgQueue = new Queue<string>(); private Queue<string> receiveMsgQueue = new Queue<string>(); private byte[] receiveByte = new byte[1024*1024]; private int receiveNum; private Socket _socket; private bool isConnected = false; void Awake() { instance = this; DontDestroyOnLoad(this.gameObject); }
void Update() { if (receiveMsgQueue.Count > 0) { print(receiveMsgQueue.Dequeue()); } } public void Connect(string ip, int port) { if(isConnected) return; if (_socket == null) _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); IPEndPoint ipPoint = new IPEndPoint(IPAddress.Parse(ip), port); try { _socket.Connect(ipPoint); isConnected = true; ThreadPool.QueueUserWorkItem(SendMsg); ThreadPool.QueueUserWorkItem(ReceiveMsg); } catch (SocketException e) { print("链接失败,错误代码是:" + e.ErrorCode + "/n错误信息:" + e.Message); } } public void Send(string info) { sendMsgQueue.Enqueue(info); }
private void SendMsg(object msg) { while (isConnected) { if (sendMsgQueue.Count > 0) { _socket.Send(Encoding.UTF8.GetBytes(sendMsgQueue.Dequeue())); } } }
private void ReceiveMsg(object msg) { while (isConnected) { if (_socket.Available > 0) { receiveNum = _socket.Receive(receiveByte); receiveMsgQueue.Enqueue(Encoding.UTF8.GetString(receiveByte,0,receiveNum)); } } } public void Close() { if (_socket != null) { _socket.Shutdown(SocketShutdown.Both); _socket.Close(); isConnected = false; } }
private void OnDestroy() { Close(); } }
|