我们有一个使用 websocket 进行连接的手机游戏。服务器是使用uWebSockets.js库的 Node.js 应用程序,客户端是使用Websocket-Sharp库的 Unity 应用程序。他们俩一起打得很好,我们没有遇到任何问题。
最近我们想启用websocket 压缩。两个库都表示它们支持按消息压缩扩展,但似乎有一些与它们不兼容的东西。因为当我们配置为使用压缩时,websocket 连接会在握手时立即关闭。
我们还使用ws库测试了客户端,并提供了具有相同结果的压缩示例。我们尝试修改 ws 压缩选项,发现当我们评论 serverMaxWindowBits 选项(默认为协商值)时,可以建立连接并且发送和接收消息没有问题。我们还询问了如何控制 uWebsockets 中的 serverMaxWindowBits。
我们尝试的最后一件事是连接一个最小的 uWS 服务器和 websocket-sharp 客户端。这是服务器的代码:
const uWS = require('uWebSockets.js');
const port = 5001;
const app = uWS.App({
}).ws('/*', {
/* Options */
compression: 1, // Setting shared compression method
maxPayloadLength: 4 * 1024,
idleTimeout: 1000,
/* Handlers */
open: (ws, req) => {
console.log('A WebSocket connected via URL: ' + req.getUrl() + …Run Code Online (Sandbox Code Playgroud) unity-game-engine websocket node.js websocket-sharp uwebsockets
我在我的Windows应用程序中使用websocket sharp dll来从GDAX服务器获取消息.到目前为止一切正常 - 消息即将到来,我正在处理它们.我被卡住的地方是消息停止发生的时候.至少我在WebSocket.OnMessage事件(https://github.com/sta/websocket-sharp)中没有找到任何可以帮助我跟踪消息何时停止的事情(我也尝试过emitonping)
现在我收到的消息有一个消息类型'Heartbeat',每秒发送一次.我想添加一个单独的计时器控件来检查心跳消息是否每秒都会到来,如果它停止了,那么我将需要重新连接服务器.但是,当消息停止发生时没有任何反应我如何跟踪它,我应该在哪里放置定时器代码来检查心跳消息何时停止?
我希望我能解释一下我被击中的情况.如果有人急于帮助我并需要更多投入,请告诉我.
更新
private void _3_Load(object sender, EventArgs e)
{
ConnectAndGetWebsocketFeedMessages();
}
public delegate void WSOpen(string text);
public delegate void WSMessage(string message);
public delegate void WSError(string text);
public delegate void WSClose(string text);
private static string _endPoint = "wss://ws-feed.gdax.com";
WebSocket ws = new WebSocket(_endPoint);
private bool IsConnected { get; set; }
private string ProductId { get; set; }
string productId = "LTC-EUR";
ConcurrentQueue<string> concurrentQueue = new ConcurrentQueue<string>();
public void SetWebSocketSharpEvents()
{
ws.Log.Level = LogLevel.Trace; …Run Code Online (Sandbox Code Playgroud) 目标是一个Web应用程序,它与安装在用户PC上的C#应用程序交换信息.客户端应用程序是websocket服务器,浏览器是websocket客户端.
最后,用户浏览器中的websocket客户端通过Angular持久创建,应用程序在PC上运行并执行某些操作.
使用的C#库是WebSocket-Sharp.websocket客户端是普通的javascript.
显然,此连接仅在本地发生,因此客户端连接到localhost.由于网站是通过HTTPS保护的,因此websocket也必须得到保护.为此,C#应用程序在启动时创建证书(实际上仅用于测试目的).
连接不起作用,因为证书不受信任.禁用客户端的所有服务器检查,但不建立连接.
这是创建服务器的部分
_server = new WebSocketServer($"wss://localhost:4649")
{
SslConfiguration =
{
ServerCertificate = Utils.Certificate.CreateSelfSignedCert(),
ClientCertificateRequired = false,
CheckCertificateRevocation = false,
ClientCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true
}
};
_server.AddWebSocketService<CommandsBehaviour>("/commands");
_server.AddWebSocketService<NotificationsBehaviour>("/notifications");
_server.Start();
Run Code Online (Sandbox Code Playgroud)
这是使用BouncyCastle创建证书的方式
private static AsymmetricKeyParameter CreatePrivateKey(string subjectName = "CN=root")
{
const int keyStrength = 2048;
// Generating Random Numbers
var randomGenerator = new CryptoApiRandomGenerator();
var random = new SecureRandom(randomGenerator);
// The Certificate Generator
var certificateGenerator = new X509V3CertificateGenerator();
// Serial Number
var serialNumber …Run Code Online (Sandbox Code Playgroud) 我制作了一个xamarin iOS/Android应用程序.这个应用程序与服务器通话websockets-sharp.
现在连接后我得到了这个错误.
03-29 16:11:14.999 I/mono-stdout(19865): 29.03.2018 16:11:14|Fatal|<>c__DisplayClass17.<startReceiving>b__16|WebSocketSharp.WebSocketException: The header of a frame cannot be read from the stream.
29.03.2018 16:11:14|Fatal|<>c__DisplayClass17.<startReceiving>b__16|WebSocketSharp.WebSocketException: The header of a frame cannot be read from the stream.
03-29 16:11:15.005 I/mono-stdout(19865): at WebSocketSharp.WebSocketFrame.processHeader (System.Byte[] header) [0x00017] in <38d3cef14c5a4fc9a92de0991034bc1a>:0
at WebSocketSharp.WebSocketFrame.processHeader (System.Byte[] header) [0x00017] in <38d3cef14c5a4fc9a92de0991034bc1a>:0
at WebSocketSharp.WebSocketFrame+<>c__DisplayClassa.<readHeaderAsync>b__9 (System.Byte[] bytes) [0x00000] in <38d3cef14c5a4fc9a92de0991034bc1a>:0
at WebSocketSharp.Ext+<>c__DisplayClass9.<ReadBytesAsync>b__8 (System.IAsyncResult ar) [0x000a2] in <38d3cef14c5a4fc9a92de0991034bc1a>:0
03-29 16:11:15.005 I/mono-stdout(19865): at WebSocketSharp.WebSocketFrame+<>c__DisplayClassa.<readHeaderAsync>b__9 (System.Byte[] bytes) [0x00000] in <38d3cef14c5a4fc9a92de0991034bc1a>:0
03-29 16:11:15.006 I/mono-stdout(19865): at WebSocketSharp.Ext+<>c__DisplayClass9.<ReadBytesAsync>b__8 …Run Code Online (Sandbox Code Playgroud) 我正在尝试使用websocket-sharp进行项目,服务器需要能够删除websocket连接.
连接由您继承的WebSocketBehavior类表示.有没有Stop或Close或Disconnect上方法WebSocketBehavior.我能找到的最接近的是
WebSocketBehavior.Context.WebSocket.Close
Run Code Online (Sandbox Code Playgroud)
所以我尝试在我的重写类中添加一个方法
public class MySocket : WebSocketBehavior
{
public void Close()
{
base.Context.WebSocket.Close();
}
}
Run Code Online (Sandbox Code Playgroud)
但是,在打开日志记录时会导致错误
2/5/2016 7:08:25 PM|Error|WebSocket.Close|This operation isn't available in: closed
Run Code Online (Sandbox Code Playgroud)
服务器如何断开/关闭WebSocket连接?
我正在用C#构建一个Unity3D客户端,用于我制作的多人游戏.服务器是用Node.js编写的,我用Javascript编写了一个运行良好的Web客户端.但是我的Unity3D客户端实现遇到了滞后问题.我正在使用websocket-sharp库,但是无法像我在带有HTML5 Websocket类的Javascript客户端上那样使用它.我相信问题在于websocket-sharp库的制作方式,目前每个Send()都会导致锁定_forSend,因此数据将像这样传输:
data1:frg1
data1:frg2
data2:frg1
data2:frg2
...
Run Code Online (Sandbox Code Playgroud)
但是在我的工作javascript实现上,它看起来像这样,因为它是真正的多线程:
data1:frg1
data2:frg1
data2:frg2
data1:frg2
Run Code Online (Sandbox Code Playgroud)
因此,我认为这是我的C#Unity实现滞后的原因,因为websockets-sharp库的行为就像这样.任何人都可以确认这是websockets-sharp库的问题或建议一个可以工作的库吗?
我现在已经构建了一个简单的Signalr Hub,我正在从Unity5项目中推送消息.鉴于SignalR2客户端不能与Unity5一起工作,我使用websocketsharp来拦截websocket框架.消息被成功推送到集线器,但是当我尝试在客户端上调用方法时,我没有获得有效负载字符串,只有消息标识符{"I": 0}
通过SignalR文档,它看起来像是最后发送的,但我不知道如何才能保持它.我确信这很简单,但对于我的生活,我无法理解.
根据要求,我已经为下面的项目添加了代码......
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using Newtonsoft.Json;
using WebSocketSharp;
namespace Assets.Scripts
{
class SignalRClient
{
private WebSocket _ws;
private string _connectionToken;
private Dictionary<string, UnTypedActionContainer> _actionMap;
private readonly string _socketUrl = "http://localhost/";
private readonly string _socket = "ws://localhost/";
public SignalRClient()
{
_actionMap = new Dictionary<string, UnTypedActionContainer>();
var webRequest = (HttpWebRequest)WebRequest.Create(_socketUrl + "/signalr/negotiate?connectionData=%5B%7B%22name%22%3A%22myHub%22%7D%5D&clientProtocol=1.3");
var response = (HttpWebResponse)webRequest.GetResponse();
using (var sr = new StreamReader(response.GetResponseStream()))
{
var payload = sr.ReadToEnd();
UnityEngine.Debug.Log(payload);
_connectionToken = …Run Code Online (Sandbox Code Playgroud) 我开始使用WebSocketSharp创建一个简单的 WebSocket 服务器。使用这个简单的代码,一切都很好:
var service = new WebSocketCustomerImageService();
var serverSocket = new WebSocketServer("ws://localhost:2000");
serverSocket.AddWebSocketService<WebSocketCustomerImageService>("/customerImageService");
serverSocket.Start();
Run Code Online (Sandbox Code Playgroud)
服务等级:
public class WebSocketCustomerImageService : WebSocketBehavior
{
protected override void OnMessage(MessageEventArgs e)
{
Send("Hello from the other side!");
}
}
Run Code Online (Sandbox Code Playgroud)
这很好用,服务器在客户端发送任何消息时做出响应,但是现在,我希望服务器发送消息而无需客户端发送任何内容。该Send()方法似乎只在WebSocketBehavior类上可用,我不直接实例化这个WebSocketCustomerImageService类。
如何访问创建的实例以使用该Send()方法或实现此目的的正确方法是什么?
我们在我们的一个应用程序中使用websocket-sharp,它与服务器上的SignalR Hub建立了websocket连接,我们能够发送文本消息并接收相同但无法发布的响应byte[].
将文本发送到服务器的代码如下:
public void TestGroupData(string groupname)
{
DataCarrier dataCarrier = new DataCarrier()
{
H = "BILHub",
M = "GetAllGroupsFor",
A = new string[] { groupname }
};
string wsPacket = JsonConvert.SerializeObject(payLoad);
this._ws.Send(wsPacket);
//this.MakeServerCall(dataCarrier);
}
Run Code Online (Sandbox Code Playgroud)
当我们尝试byte[]使用以下代码发送时,它不会通过:
public void TestFileData()
{
try
{
// Read the file data
Console.WriteLine("Started reading file");
string fileName = @"C:\Saurabh\Data\Song.mp3";
byte[] file = File.ReadAllBytes(fileName);
DataCarrier dataCarrier = new DataCarrier()
{
H = "BILHub",
M = "SendFile",
A = new object[] { file …Run Code Online (Sandbox Code Playgroud) 我需要在 C# 中创建一个到特定 url(无法显示)的 websocket。是否有类似于 Java 中的 WebSocket API 或 C# 中的 libwebsockets 的东西?
我已经按照一些SO答案尝试使用WebSocketSharp和ChilKat。还尝试使用 Microsoft 的 WebSocket 命名空间。但总是收到“未授权”错误 401。我还尝试执行 Http get 并尝试按照 MDN 文档中创建 WebSocket 服务器的教程添加标头以将套接字升级到 Websocket,但只获得重定向的网页作为回报。这是我用于 HTTP 升级请求的代码。我是 c# 初学者。
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls
| SecurityProtocolType.Tls11
| SecurityProtocolType.Tls12
| SecurityProtocolType.Ssl3;
ServicePointManager.ServerCertificateValidationCallback += (se, cert, chain, sslerror) =>
{
return true;
};
var http = (HttpWebRequest)WebRequest.Create(new Uri(baseAddress));
http.AllowAutoRedirect = false;
http.UseDefaultCredentials = true;
http.PreAuthenticate = true;
http.Credentials = CredentialCache.DefaultCredentials;
http.Proxy.Credentials = CredentialCache.DefaultCredentials;
http.Accept = "application/json";
http.ContentType = …Run Code Online (Sandbox Code Playgroud) websocket-sharp ×10
c# ×7
websocket ×4
signalr ×2
xamarin ×2
exception ×1
node.js ×1
sockets ×1
unity5 ×1
uwebsockets ×1