Unity使用WebSocket(基于BaseHTTP插件)
2018-01-07 14:59
363 查看
服务器:使用c#写的,用来持续给一个端口发数据
这个是用来进行数据的接收
插件地址:http://download.csdn.net/download/agroupofruffian/10192849
using System; using System.Text; using System.Net; using System.Net.Sockets; using System.Text.RegularExpressions; using System.Security.Cryptography; using System.Threading; namespace WebSocketServer { class Program { static string byte_to_string(byte[] b) { string s = ""; foreach (byte _b in b) { s += _b.ToString(); } return s; } static void Main(string[] args) { int port = 1818; byte[] buffer = new byte[1024]; IPEndPoint localEP = new IPEndPoint(IPAddress.Any, port); Socket listener = new Socket(localEP.Address.AddressFamily, SocketType.Stream, ProtocolType.Tcp); try { listener.Bind(localEP); listener.Listen(10); Console.WriteLine("等待客户端连接...."); Socket sc = listener.Accept();//接受一个连接 Console.WriteLine("接受到了客户端:" + sc.RemoteEndPoint.ToString() + "连接...."); //握手 int length = sc.Receive(buffer);//接受客户端握手信息 sc.Send(PackHandShakeData(GetSecKeyAccetp(buffer, length))); Console.WriteLine("已经发送握手协议了...."); while (true) { Thread.Sleep(1000); //主动发送数据 string lines = "{\"info\":[{\"area\":11,\"x\":80,\"y\":50},{\"area\":5,\"x\":76,\"y\":48}]}"; Console.WriteLine("发送数据:“" + lines + "” 至客户端...."); sc.Send(PackData(lines)); } //接受客户端数据 Console.WriteLine("等待客户端数据...."); length = sc.Receive(buffer);//接受客户端信息 string clientMsg = AnalyticData(buffer, length); Console.WriteLine("接受到客户端数据:" + clientMsg); //发送数据 //string sendMsg = "您好," + clientMsg; //Console.WriteLine("发送数据:“" + sendMsg + "” 至客户端...."); //sc.Send(PackData(sendMsg)); Console.WriteLine("演示Over!"); Console.Read(); } catch (Exception e) { Console.WriteLine(e.ToString()); } } /// <summary> /// 打包握手信息 /// </summary> /// <param name="secKeyAccept">Sec-WebSocket-Accept</param> /// <returns>数据包</returns> private static byte[] PackHandShakeData(string secKeyAccept) { var responseBuilder = new StringBuilder(); responseBuilder.Append("HTTP/1.1 101 Switching Protocols" + Environment.NewLine); responseBuilder.Append("Upgrade: websocket" + Environment.NewLine); responseBuilder.Append("Connection: Upgrade" + Environment.NewLine); responseBuilder.Append("Sec-WebSocket-Accept: " + secKeyAccept + Environment.NewLine + Environment.NewLine); return Encoding.UTF8.GetBytes(responseBuilder.ToString()); } /// <summary> /// 生成Sec-WebSocket-Accept /// </summary> /// <param name="handShakeText">客户端握手信息</param> /// <returns>Sec-WebSocket-Accept</returns> private static string GetSecKeyAccetp(byte[] handShakeBytes, int bytesLength) { string handShakeText = Encoding.UTF8.GetString(handShakeBytes, 0, bytesLength); string key = string.Empty; Regex r = new Regex(@"Sec\-WebSocket\-Key:(.*?)\r\n"); Match m = r.Match(handShakeText); if (m.Groups.Count != 0) { key = Regex.Replace(m.Value, @"Sec\-WebSocket\-Key:(.*?)\r\n", "$1").Trim(); } byte[] encryptionString = SHA1.Create().ComputeHash(Encoding.ASCII.GetBytes(key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11")); return Convert.ToBase64String(encryptionString); } /// <summary> /// 解析客户端数据包 /// </summary> /// <param name="recBytes">服务器接收的数据包</param> /// <param name="recByteLength">有效数据长度</param> /// <returns></returns> private static string AnalyticData(byte[] recBytes, int recByteLength) { if (recByteLength < 2) { return string.Empty; } bool fin = (recBytes[0] & 0x80) == 0x80; // 1bit,1表示最后一帧 if (!fin) { return string.Empty;// 超过一帧暂不处理 } bool mask_flag = (recBytes[1] & 0x80) == 0x80; // 是否包含掩码 if (!mask_flag) { return string.Empty;// 不包含掩码的暂不处理 } int payload_len = recBytes[1] & 0x7F; // 数据长度 byte[] masks = new byte[4]; byte[] payload_data; if (payload_len == 126) { Array.Copy(recBytes, 4, masks, 0, 4); payload_len = (UInt16)(recBytes[2] << 8 | recBytes[3]); payload_data = new byte[payload_len]; Array.Copy(recBytes, 8, payload_data, 0, payload_len); } else if (payload_len == 127) { Array.Copy(recBytes, 10, masks, 0, 4); byte[] uInt64Bytes = new byte[8]; for (int i = 0; i < 8; i++) { uInt64Bytes[i] = recBytes[9 - i]; } UInt64 len = BitConverter.ToUInt64(uInt64Bytes, 0); payload_data = new byte[len]; for (UInt64 i = 0; i < len; i++) { payload_data[i] = recBytes[i + 14]; } } else { Array.Copy(recBytes, 2, masks, 0, 4); payload_data = new byte[payload_len]; Array.Copy(recBytes, 6, payload_data, 0, payload_len); } for (var i = 0; i < payload_len; i++) { payload_data[i] = (byte)(payload_data[i] ^ masks[i % 4]); } return Encoding.UTF8.GetString(payload_data); } /// <summary> /// 打包服务器数据 /// </summary> /// <param name="message">数据</param> /// <returns>数据包</returns> private static byte[] PackData(string message) { byte[] contentBytes = null; byte[] temp = Encoding.UTF8.GetBytes(message); if (temp.Length < 126) { contentBytes = new byte[temp.Length + 2]; contentBytes[0] = 0x81; contentBytes[1] = (byte)temp.Length; Array.Copy(temp, 0, contentBytes, 2, temp.Length); } else if (temp.Length < 0xFFFF) { contentBytes = new byte[temp.Length + 4]; contentBytes[0] = 0x81; contentBytes[1] = 126; contentBytes[2] = (byte)(temp.Length & 0xFF); contentBytes[3] = (byte)(temp.Length >> 8 & 0xFF); Array.Copy(temp, 0, contentBytes, 4, temp.Length); } else { // 暂不处理超长内容 } return contentBytes; } } }客户端:
这个是用来进行数据的接收
using System; using UnityEngine; using System.Collections; using System.Collections.Generic; using System.Threading; using BestHTTP; using BestHTTP.WebSocket; public class WabData { /// <summary> /// The WebSocket address to connect /// </summary> private readonly string address = "ws://192.168.199.208:1818"; /// <summary> /// Default text to send /// </summary> private string _msgToSend = "Hello World!"; /// <summary> /// Debug text to draw on the gui /// </summary> private string _text = string.Empty; /// <summary> /// Saved WebSocket instance /// </summary> private WebSocket _webSocket; private Queue<DataInfo> _msgQueue = new Queue<DataInfo>(); public Queue<DataInfo> MsgQueue { get { return _msgQueue; } } public WebSocket WebSocket { get { return _webSocket; } } public string Address { get { return address; } } public string Text { get { return _text; } } public string MsgToSend { get { return _msgToSend; } set { _msgToSend = value; SendMsg(value); } } public void OpenWebSocket() { if (_webSocket == null) { // Create the WebSocket instance _webSocket = new WebSocket(new Uri(address)); if (HTTPManager.Proxy != null) _webSocket.InternalRequest.Proxy = new HTTPProxy(HTTPManager.Proxy.Address, HTTPManager.Proxy.Credentials, false); // Subscribe to the WS events _webSocket.OnOpen += OnOpen; _webSocket.OnMessage += OnMessageReceived; _webSocket.OnClosed += OnClosed; _webSocket.OnError += OnError; // Start connecting to the server _webSocket.Open(); } } public void SendMsg(string msg) { // Send message to the server _webSocket.Send(msg); } public void CloseSocket() { // Close the connection _webSocket.Close(1000, "Bye!"); } /// <summary> /// Called when the web socket is open, and we are ready to send and receive data /// </summary> void OnOpen(WebSocket ws) { Debug.Log("-WebSocket Open!\n"); } /// <summary> /// Called when we received a text message from the server /// </summary> void OnMessageReceived(WebSocket ws, string message) { DataInfo datainfo = JsonUtility.FromJson<DataInfo>(message); if (datainfo != null) _msgQueue.Enqueue(datainfo); } /// <summary> /// Called when the web socket closed /// </summary> void OnClosed(WebSocket ws, UInt16 code, string message) { Debug.Log(string.Format("-WebSocket closed! Code: {0} Message: {1}\n", code, message)); _webSocket = null; } /// <summary> /// Called when an error occured on client side /// </summary> void OnError(WebSocket ws, Exception ex) { string errorMsg = string.Empty; if (ws.InternalRequest.Response != null) errorMsg = string.Format("Status Code from Server: {0} and Message: {1}", ws.InternalRequest.Response.StatusCode, ws.InternalRequest.Response.Message); Debug.Log(string.Format("-An error occured: {0}\n",ex != null ? ex.Message : "Unknown Error " + errorMsg)); _webSocket = null; } } //{"info":[{"area":11,"x":80,"y":50},{"area":5,"x":76,"y":48}]} [System.Serializable] public class DataInfo { public Data[] info; } [System.Serializable] public class Data { public int area; public int x; public int y; }这个是用来获得上面存储的数据:
using System; using UnityEngine; using BestHTTP; using BestHTTP.WebSocket; public class WebSocketSimpet : MonoBehaviour { #region Private Fields /// <summary> /// The WebSocket address to connect /// </summary> string _address; /// <summary> /// Default text to send /// </summary> string _msgToSend; /// <summary> /// Debug text to draw on the gui /// </summary> string _text; /// <summary> /// GUI scroll position /// </summary> Vector2 _scrollPos; private WabData _wabData; #endregion #region Unity Events void Start() { _wabData = new WabData(); _address = _wabData.Address; _msgToSend = _wabData.MsgToSend; _text = _wabData.Text; } void Update() { if (_wabData.MsgQueue.Count > 0) { DataInfo info = _wabData.MsgQueue.Dequeue(); string json = JsonUtility.ToJson(info); Debug.Log(json); } } void OnDestroy() { if (_wabData.WebSocket != null) _wabData.WebSocket.Close(); } void OnGUI() { _address = GUILayout.TextField(_address); if (_wabData.WebSocket == null && GUILayout.Button("Open Web Socket")) { _wabData.OpenWebSocket(); _text += "Opening Web Socket...\n"; } if (_wabData.WebSocket != null && _wabData.WebSocket.IsOpen) { if (GUILayout.Button("Send", GUILayout.MaxWidth(70))) { _text += "Sending message...\n"; // Send message to the server _wabData.WebSocket.Send(_msgToSend); } if (GUILayout.Button("Close")) { // Close the connection _wabData.WebSocket.Close(1000, "Bye!"); } } } #endregion }
插件地址:http://download.csdn.net/download/agroupofruffian/10192849
相关文章推荐
- 基于SuperSocket实现的WebSocket服务器 和Unity中使用Websocket
- 使用基于jquery的gamequery插件做JS乒乓球游戏
- Warensoft Unity3D通信库使用向导2-利用UnityHttpClient类实现Http通信
- 一个基于jQuery的树型插件(OrangeTree)使用介绍
- Chosen 基于jquery的选择框插件使用方法
- 使用XMLHttpRequest结合struts2实现Ajax异步调用的例子+json插件
- EclEMMA(基于Eclipse覆盖率测试插件)在JBoss上的使用说明
- 基于jquery的上传插件Uploadify 3.1.1在MVC3中的使用:上传大文件的IO Error问题
- 基于jquery的上传插件Uploadify 3.1.1在MVC3中的使用
- 使用struts2-convention-plugin-2.2.1.1.jar插件实现基于注解的配置。
- apache服务器安装以及使用passenger插件部署rails应用,基于ubuntu 12.04 LTS
- unity深入研究--开发之C#使用Socket与HTTP连接服务器传输数据包
- 使用 HttpModel与现有基于共享登录信息( Cookie )的网站进行集成
- 原创基于标签的表单验证插件,有源码,有注释,有实例,使用超级方便。
- 基于jQuery的nyroModal模态对话框插件的使用,及IFrame方式窗口的关闭问题
- unity下2d和3d混合使用教程,插件为OrtHello (一)
- 如何配置基于eclipse的easy structs插件,并介绍了如何结合使用easy structs和eclipes来开发struts的应用
- 使用uploadify上传插件时遇到 NetworkError: 403 Forbidden http://xxxx/xxxx/ 错误
- 基于jquery的lazy loader插件实现图片的延迟加载[简单使用]