首页 > 代码库 > 基于SuperSocket实现的WebSocket服务器 和Unity中使用Websocket
基于SuperSocket实现的WebSocket服务器 和Unity中使用Websocket
孙广东 2016.10.15
http://blog.csdn.NET/u010019717
说一下 Unity客户端的库:
1、websocket-sharp AS中已经下架了, https://github.com/sta/websocket-sharp 但是Unity的官方插件 : Simple Web Sockets for Unity WebGL 就是使用的它
2、Simple Web Sockets for Unity WebGL(推荐) Unity官方退出的插件
3、Best HTTP (Basic Edition) 这个插件不止一次提到了, 就是很强大,提供了 Websocket的支持!
4、还有提到的: WebSocket4Net
http://websocket4net.codeplex.com/
WebSocket4Net.dll 这个DLL复制到 Unity3D里面刚才新建的 Plugin文件夹内(注意Unity不得使用中文)
ref: http://www.cnblogs.com/xmcrew/p/3747441.html
注: 我使用 Simple WebSockets for Unity WebGL 和 WebSuperSocket 一起使用能连接,但是不能 发送和接收,(插件包含的太老了, 可以在github 看到新的内容)
然后我就是 客户端使用 BestHttp 插件, 导入后更改Bug 之后就可以了。
C# 控制台程序
补充: 下载导入项目中可以 使用 程序包管理器控制台中输入:
Install-Package SuperSocket
或者后面指定版本: -Version 1.6.6
Install-Package SuperWebSocket
http://superwebsocket.codeplex.com/。 代码中包含了一个简单的聊天示例。可以供我们参考,学习。
class Program { static void Main(string[] args) { Console.WriteLine("Press any key to start the WebSocketServer!"); Console.ReadKey(); Console.WriteLine(); var appServer = new WebSocketServer(); //Setup the appServer if (!appServer.Setup(2012)) //Setup with listening port { Console.WriteLine("Failed to setup!"); Console.ReadKey(); return; } appServer.NewSessionConnected += delegate(WebSocketSession session) { Console.WriteLine("新玩家加入: " + session.SessionID); session.Send("新玩家加入: " + session.SessionID); }; appServer.SessionClosed += delegate(WebSocketSession session, CloseReason value) { Console.WriteLine("玩家离开: " + session.SessionID); session.Send("玩家离开: " + session.SessionID); }; appServer.NewMessageReceived += delegate(WebSocketSession session, string value) { Console.WriteLine(session.SessionID + "说话: " + value); session.Send(session.SessionID + "说话: " + value); }; Console.WriteLine(); //Try to start the appServer if (!appServer.Start()) { Console.WriteLine("Failed to start!"); Console.ReadKey(); return; } Console.WriteLine("The server started successfully, press key ‘q‘ to stop it!"); while (Console.ReadKey().KeyChar != ‘q‘) { Console.WriteLine(); continue; } //Stop the appServer appServer.Stop(); Console.WriteLine(); Console.WriteLine("The server was stopped!"); Console.ReadKey(); } }
using System; using UnityEngine; using BestHTTP; using BestHTTP.WebSocket; public class WebSocketSample : MonoBehaviour { #region Private Fields /// <summary> /// The WebSocket address to connect /// </summary> string address = "ws://127.0.0.1:2012";// "ws://echo.websocket.org"; /// <summary> /// Default text to send /// </summary> string msgToSend = "Hello World!"; /// <summary> /// Debug text to draw on the gui /// </summary> string Text = string.Empty; /// <summary> /// Saved WebSocket instance /// </summary> WebSocket webSocket; /// <summary> /// GUI scroll position /// </summary> Vector2 scrollPos; #endregion #region Unity Events void OnDestroy() { if (webSocket != null) webSocket.Close(); } void OnGUI() { scrollPos = GUILayout.BeginScrollView(scrollPos); GUILayout.Label(Text); GUILayout.EndScrollView(); GUILayout.Space(5); GUILayout.FlexibleSpace(); address = GUILayout.TextField(address); if (webSocket == null && GUILayout.Button("Open Web Socket")) { // 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 += one rror; // Start connecting to the server webSocket.Open(); Text += "Opening Web Socket...\n"; } if (webSocket != null && webSocket.IsOpen) { GUILayout.Space(10); GUILayout.BeginHorizontal(); msgToSend = GUILayout.TextField(msgToSend); if (GUILayout.Button("Send", GUILayout.MaxWidth(70))) { Text += "Sending message...\n"; // Send message to the server webSocket.Send(msgToSend); } GUILayout.EndHorizontal(); GUILayout.Space(10); if (GUILayout.Button("Close")) { // Close the connection webSocket.Close(1000, "Bye!"); } } } #endregion #region WebSocket Event Handlers /// <summary> /// Called when the web socket is open, and we are ready to send and receive data /// </summary> void OnOpen(WebSocket ws) { Text += string.Format("-WebSocket Open!\n"); } /// <summary> /// Called when we received a text message from the server /// </summary> void OnMessageReceived(WebSocket ws, string message) { Text += string.Format("-Message received: {0}\n", message); } /// <summary> /// Called when the web socket closed /// </summary> void OnClosed(WebSocket ws, UInt16 code, string message) { Text += string.Format("-WebSocket closed! Code: {0} Message: {1}\n", code, message); webSocket = null; } /// <summary> /// Called when an error occured on client side /// </summary> void one rror(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); Text += string.Format("-An error occured: {0}\n", (ex != null ? ex.Message : "Unknown Error " + errorMsg)); webSocket = null; } #endregion }
基于SuperSocket实现的WebSocket服务器 和Unity中使用Websocket