为了在 C# 中实现我的 websocket 服务器,我使用了 Alchemy 框架。我被这个问题困住了。在方法 OnReceive 中,当我尝试反序列化 json 对象时,我得到一个 FormatException:
“输入字符串的格式不正确。” (也许它在英语中有所不同,但我收到了本地化的异常消息,这是我的翻译:P)。奇怪的是,当我打印出 context.DataFrame
时,我得到: 111872281.1341000479.1335108793.1335108793.1335108793.1; __ad
这是浏览器发送的 cookie 的子字符串: __gutp=entrystamp%3D1288455757%7Csid%3D65a51a83cbf86945d0fd994e15eb94f9%7Cstamp%3D1288456520%7Contime%3D155; __utma=111872281.1341000479.1335108793.1335108793.1335108793.1; __adtaily_ui=cupIiq90q9
。
JS代码:
// I'm really not doing anything more than this
var ws = new WebSocket("ws://localhost:8080");
C#代码:
static void Main(string[] args) {
int port = 8080;
WebSocketServer wsServer = new WebSocketServer(port, IPAddress.Any) {
OnReceive = OnReceive,
OnSend = OnSend,
OnConnect = OnConnect,
OnConnected = OnConnected,
OnDisconnect = OnDisconnect,
TimeOut = new TimeSpan(0, 5, 0)
};
wsServer.Start();
Console.WriteLine("Server started listening on port: " + port + "...");
string command = string.Empty;
while (command != "exit") {
command = Console.ReadLine();
}
Console.WriteLine("Server stopped listening on port: " + port + "...");
wsServer.Stop();
Console.WriteLine("Server exits...");
}
public static void OnReceive(UserContext context) {
string json = "";
dynamic obj;
try {
json = context.DataFrame.ToString();
Console.WriteLine(json);
obj = JsonConvert.DeserializeObject(json);
} catch (Exception e) {
Console.WriteLine(e.Message);
Console.WriteLine(e.StackTrace);
return;
}
}
在 C# 方面,我使用的是 Newtonsoft.Json,尽管这个库没有问题...
编辑: 还有一件事 - 我浏览了这里的代码:https://github.com/Olivine-Labs/Alchemy-Websockets-Example 并没有发现任何东西 - 我的意思是,我正在按照作者在本教程中所做的方式做所有事情......
编辑: 我在 Firefox v 17.0.1 中测试了上面的代码,它没有运行,所以我在 google chrome 下测试它,它可以运行。那么让我重新表述一下这个问题 - 可以在 js 中进行哪些更改,以便 firefox 不会发送上述字符串?
最佳答案
我遇到了同样的问题 - 只需更换
var ws = new WebSocket("ws://localhost:8080");
与
var ws = new WebSocket("ws://127.0.0.1:8080");
为我解决了这个问题。
关于c# - Firefox 中的 WebSocket,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14234573/