使用C#连接到websocket(我可以使用JavaScript连接,但C#给出状态代码200错误) [英] Connecting to websocket using C# (I can connect using JavaScript, but C# gives Status code 200 error)

查看:214
本文介绍了使用C#连接到websocket(我可以使用JavaScript连接,但C#给出状态代码200错误)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是websocket领域的新手。

I am new in the area of websocket.

我可以使用以下代码使用JavaScript连接到websocket服务器:

I can connect to websocket server using JavaScript using this code:

var webSocket = new WebSocket(url);

但是对于我的应用程序,我需要使用c#连接到同一台服务器。我使用的代码是:

But for my application, I need to connect to the same server using c#. The code I am using is:

ClientWebSocket webSocket = null;
webSocket = new ClientWebSocket();
await webSocket.ConnectAsync(new Uri(url), CancellationToken.None);

错误后第3行代码结果:

3rd line of the code results following error:


当预期状态代码101时服务器返回状态代码200

"Server returned status code 200 when status code 101 was expected"

稍后调查,我意识到服务器在连接过程中无法以某种方式将http协议切换到websocket协议。

After little bit of survey, I realised that somehow server can't switch http protocol to websocket protocol during connection process.

我在C#代码中做了什么愚蠢或者出了什么问题与服务器。我没有任何访问服务器的权限,因为我使用的网址是第三方网址。

Am I doing anything stupid in my C# code or there is something going wrong with the server. I don't have any access to the server, as the url I am using is a third party one .

您能否就此问题向我提出任何建议?

Could you please give me any suggestion regarding the issue?

推荐答案

使用 WebSocketSharp库并轻松连接:

WebSocket客户端

using System;
using WebSocketSharp;

namespace Example
{
  public class Program
  {
    public static void Main (string[] args)
    {
      using (var ws = new WebSocket ("ws://dragonsnest.far/Laputa")) {
        ws.OnMessage += (sender, e) =>
          Console.WriteLine ("Laputa says: " + e.Data);

        ws.Connect ();
        ws.Send ("BALUS");
        Console.ReadKey (true);
      }
    }
  }
}

第1步

必需的命名空间。

using WebSocketSharp;

WebSocketSharp命名空间中存在WebSocket类。

The WebSocket class exists in the WebSocketSharp namespace.

第2步

使用要连接的WebSocket URL创建WebSocket类的新实例。

Creating a new instance of the WebSocket class with the WebSocket URL to connect.

using (var ws = new WebSocket ("ws://example.com")) {
  ...
}

WebSocket类继承System.IDisposable接口,因此您可以使用using语句。当控件离开使用块时,WebSocket连接将以关闭状态1001(离开)关闭。

The WebSocket class inherits the System.IDisposable interface, so you can use the using statement. And the WebSocket connection will be closed with close status 1001 (going away) when the control leaves the using block.

第3步

设置WebSocket事件。

Setting the WebSocket events.

建立WebSocket连接时发生 WebSocket.OnOpen 事件。

A WebSocket.OnOpen event occurs when the WebSocket connection has been established.

ws.OnOpen += (sender, e) => {
  ...
};

e已作为 System.EventArgs.Empty ,所以你不需要使用它。

e has passed as the System.EventArgs.Empty, so you don't need to use it.

当WebSocket收到消息时,会发生 WebSocket.OnMessage 事件。

A WebSocket.OnMessage event occurs when the WebSocket receives a message.

ws.OnMessage += (sender, e) => {
  ...
};

e已作为WebSocketSharp.MessageEventArgs传递。

e has passed as a WebSocketSharp.MessageEventArgs.

e.Type属性返回表示消息类型的WebSocketSharp.Opcode.Text或WebSocketSharp.Opcode.Binary。因此,通过检查它,您可以确定应该使用哪个项目。

e.Type property returns either WebSocketSharp.Opcode.Text or WebSocketSharp.Opcode.Binary that represents the type of the message. So by checking it, you can determine which item you should use.

如果它返回Opcode.Text,您应该使用返回字符串的e.Data属性(表示短信)。

If it returns Opcode.Text, you should use e.Data property that returns a string (represents the Text message).

或者如果它返回 Opcode.Binary ,你应该使用返回a的e.RawData属性byte [](表示二进制消息)。

Or if it returns Opcode.Binary, you should use e.RawData property that returns a byte[] (represents the Binary message).

if (e.Type == Opcode.Text) {
  // Do something with e.Data.
  ...

  return;
}

if (e.Type == Opcode.Binary) {
  // Do something with e.RawData.
  ...

  return;
}



WebSocket.OnError 事件



当WebSocket出错时,会发生 WebSocket.OnError 事件。

ws.OnError += (sender, e) => {
  ...
};

e已作为传递给WebSocketSharp.ErrorEventArgs

e.Message属性返回一个表示错误消息的字符串。

e.Message property returns a string that represents the error message.

如果错误是由于例外,e.Exception属性返回导致错误的 System.Exception 实例。

If the error is due to an exception, e.Exception property returns a System.Exception instance that caused the error.

WebSocket连接关闭时发生WebSocket.OnClose事件。

A WebSocket.OnClose event occurs when the WebSocket connection has been closed.

ws.OnClose += (sender, e) => {
  ...
};

e已作为传递给WebSocketSharp.CloseEventArgs

e.Code属性返回一个ushort,表示状态代码,表示关闭的原因,e.Reason属性返回一个字符串,表示关闭的原因。

e.Code property returns a ushort that represents the status code indicating the reason for the close, and e.Reason property returns a string that represents the reason for the close.

第4步

连接到WebSocket服务器。

Connecting to the WebSocket server.

ws.Connect ();

如果要异步连接到服务器,则应使用WebSocket.ConnectAsync()方法。

If you would like to connect to the server asynchronously, you should use the WebSocket.ConnectAsync () method.

第5步

将数据发送到WebSocket服务器。

Sending data to the WebSocket server.

ws.Send (data);

WebSocket.Send方法已超载。

The WebSocket.Send method is overloaded.

您可以使用 WebSocket.Send(字符串),WebSocket.Send(byte []) WebSocket.Send(System.IO。 FileInfo)发送数据的方法。

You can use the WebSocket.Send (string), WebSocket.Send (byte[]), or WebSocket.Send (System.IO.FileInfo) method to send the data.

如果要异步发送数据,则应使用WebSocket.SendAsync方法。 / p>

If you would like to send the data asynchronously, you should use the WebSocket.SendAsync method.

ws.SendAsync (data, completed);

如果您想在发送完成后做某事,您应该将已完成设置为任何操作< bool> 委托。

And also if you would like to do something when the send is complete, you should set completed to any Action<bool> delegate.

第6步

关闭WebSocket连接。

Closing the WebSocket connection.

ws.Close (code, reason);

如果要显式关闭连接,则应使用 WebSocket .Close 方法。

If you would like to close the connection explicitly, you should use the WebSocket.Close method.

WebSocket.Close方法重载。

The WebSocket.Close method is overloaded.

你可以使用WebSocket.Close(),WebSocket.Close(ushort),WebSocket.Close(WebSocketSharp.CloseStatusCode),WebSocket.Close(ushort,string)或WebSocket.Close(WebSocketSharp.CloseStatusCode,string)方法来关闭连接。

You can use the WebSocket.Close (), WebSocket.Close (ushort), WebSocket.Close (WebSocketSharp.CloseStatusCode), WebSocket.Close (ushort, string), or WebSocket.Close (WebSocketSharp.CloseStatusCode, string) method to close the connection.

如果要异步关闭连接,则应使用 WebSocket.CloseAsync 方法。

If you would like to close the connection asynchronously, you should use the WebSocket.CloseAsync method.

这篇关于使用C#连接到websocket(我可以使用JavaScript连接,但C#给出状态代码200错误)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆