转自:http://www.cnblogs.com/daxiaxiaohao/p/4402063.html
在刚刚开发Unity项目的过程中,需要用到即时通信功能来完成服务器与客户端自定义的数据结构封装。
现在将部分主要功能的实现代码抽取出来实现了可以异步Socket请求的技术Demo。
客户端脚本ClientScript
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 |
/// <summary> /// Client Script. /// Created By 蓝鸥3G 2014.08.23 /// </summary> using UnityEngine; using System.Collections; public class ClientScript: MonoBehaviour { string msg = ""; // Use this for initialization LOSocket client; void Start () { client = LOSocket.GetSocket(LOSocket.LOSocketType.CLIENT); client.InitClient ("127.0.0.1", 2222, ((string content) => { //收到服务器的回馈信息 })); } void OnGUI() { msg = GUI.TextField(new Rect(0, 0, 500, 40), msg); if(GUI.Button(new Rect(0, 50, 100, 30), "Send")) { client.SendMessage (msg); } } } |
服务器端脚本
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 |
/// <summary> /// Server Script. /// Created By 蓝鸥3G 2014.08.23 /// </summary> /// /// using UnityEngine; using System.Collections; public class ServerScript : MonoBehaviour { private string receive_str; LOSocket server; // Use this for initialization void Start () { server = LOSocket.GetSocket(LOSocket.LOSocketType.SERVER); //初始化服务器 server.InitServer((string content) => { receive_str = content; }); } void OnGUI() { if (receive_str != null) { GUILayout.Label (receive_str); } } } |
LOSocket框架
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 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 |
/// <summary> /// LOSocket. /// Created By 蓝鸥3G 2014.08.23 /// </summary> /// /// using UnityEngine; using System.Collections; using System.Net; using System.Net.Sockets; using System.Text; //收到消息后的委托回调 public delegate void ReceiveCallBack(string content); public class LOSocket{ //可以创建的Socket端口类型 public enum LOSocketType { CLIENT = 0, SERVER = 1, } #region --------取消构造器 private LOSocket() { } #endregion #region --------公共代码 //通过静态方法获取不同的端口类型 public static LOSocket GetSocket(LOSocket.LOSocketType type) { LOSocket socket = null; switch (type) { case LOSocketType.CLIENT: { //创建一个新的客户端 socket = new LOSocket (); break; } case LOSocketType.SERVER: { //获取服务端 socket = GetServer (); break; } } return socket; } #endregion #region --------客户端部分代码 private Socket clientSocket; //声明客户端收到服务端返回消息后的回调委托函数 private ReceiveCallBack clientReceiveCallBack; //用来存储服务端返回的消息数据 byte[] Buffer = new byte[1024]; //初始化客户端Socket信息 public void InitClient(string ip,int port,ReceiveCallBack ccb) { this.clientReceiveCallBack = ccb; this.clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); IPAddress address = IPAddress.Parse (ip); IPEndPoint ep = new IPEndPoint (address, port); this.clientSocket.Connect(ep); //开始异步等待接收服务端消息 this.clientSocket.BeginReceive (Buffer, 0, Buffer.Length, SocketFlags.None, new System.AsyncCallback(ReceiveFromServer), this.clientSocket); } //收到服务端返回消息后的回调函数 void ReceiveFromServer(System.IAsyncResult ar) { //获取当前正在工作的Socket对象 Socket worker = ar.AsyncState as Socket; int ByteRead=0; try { //接收完毕消息后的字节数 ByteRead = worker.EndReceive(ar); } catch (System.Exception ex) { this.clientReceiveCallBack (ex.ToString ()); } if (ByteRead > 0) { string Content = Encoding.Default.GetString (Buffer); //通过回调函数将消息返回给调用者 this.clientReceiveCallBack (Content); } //继续异步等待接受服务器的返回消息 worker.BeginReceive(Buffer, 0, Buffer.Length, SocketFlags.None, new System.AsyncCallback(ReceiveFromServer), worker); } //客户端主动发送消息 public void SendMessage(string message) { if (message == null) return; message += "\r\n"; byte[] sendData = Encoding.UTF8.GetBytes (message); //异步发送消息请求 clientSocket.BeginSend (sendData, 0, sendData.Length, SocketFlags.None, new System.AsyncCallback (SendToServer), clientSocket); } //发送消息结束的回调函数 void SendToServer(System.IAsyncResult ar) { Socket worker = ar.AsyncState as Socket; worker.EndSend (ar); } #endregion #region -------服务器部分代码 //服务器端收到消息的存储空间 byte[] ReceiveBuffer = new byte[1024]; //服务器收到消息后的回调委托 private ReceiveCallBack callback; //单例模式 private static LOSocket serverSocket; private static LOSocket GetServer() { if (serverSocket == null) { serverSocket = new LOSocket(); } return serverSocket; } //初始化服务器信息 public void InitServer(ReceiveCallBack cb) { this.callback = cb; // 1. Socket server_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); // 2. IPEndPoint endPoint = new IPEndPoint(IPAddress.Any, 2222); // 3. server_socket.Bind(endPoint); // 4. server_socket.Listen(10); // 5.开始异步等待客户端的请求链接 server_socket.BeginAccept (new System.AsyncCallback (Accept), server_socket); this.callback ("开启服务器" + endPoint.ToString()); } //接受到客户端的链接请求后的回调函数 void Accept(System.IAsyncResult ar){ //获取正在工作的Socket对象 Socket socket = ar.AsyncState as Socket; //存储异步操作的信息,以及用户自定义的数据 Socket worker = socket.EndAccept(ar); SocketError error; //开始异步接收客户端发送消息内容 worker.BeginReceive (ReceiveBuffer, 0, ReceiveBuffer.Length, SocketFlags.None, new System.AsyncCallback (Receive), worker); //继续异步等待新的客户端链接请求 socket.BeginAccept(new System.AsyncCallback(Accept), socket); } //服务端收到客户端的消息后的回调函数 void Receive(System.IAsyncResult ar) { //获取正在工作的Socket对象 Socket worker = ar.AsyncState as Socket; int ByteRead=0; try { ByteRead = worker.EndReceive(ar); } catch (System.Exception ex) { this.callback (ex.ToString ()); } if (ByteRead > 0) { string Content = Encoding.Default.GetString (ReceiveBuffer); this.callback (Content); } //继续异步等待客户端的发送消息请求 worker.BeginReceive(ReceiveBuffer, 0, ReceiveBuffer.Length, SocketFlags.None, new System.AsyncCallback(Receive), worker); } #endregion } |
- 本文固定链接: http://www.u3d8.com/?p=221
- 转载请注明: 网虫虫 在 u3d8.com 发表过