C#原⽣WebSocket客户端ClientWebSocket使⽤
WebSocket框架有很多,最近在搞SocketServer服务器,服务端⽤的是Supersocket,客户端封装在Dll⾥⾯供第三⽅调⽤,如果dll⾥⾯引⽤第三⽅框架WebSocket的话,引⽤dll时还需要引⽤⼀堆额外的包,这就显得有点臃肿,因为dll⾥⾯的WebSocket只有客户端,所以考虑⽤原⽣的ClientWebSocket即可;
连接并发送消息:
public static ClientWebSocket clientWebSocket;
public static Uri serverUri;
public SocketClient(string ip, int port)
{var webSocketUrl = $@"ws://{ip}:{port}";
clientWebSocket = new ClientWebSocket();
serverUri = new Uri(webSocketUrl);
clientWebSocket.ConnectAsync(serverUri, CancellationToken.None).Wait();
}
public async Task SendMessageAsync(string Msg)
{
if(clientWebSocket.State != WebSocketState.Open)
{
await clientWebSocket.ConnectAsync(serverUri, CancellationToken.None);
}
if (clientWebSocket.State == WebSocketState.Open)
{
ArraySegment<byte> bytesToSend = new ArraySegment<byte>(Encoding.UTF8.GetBytes(Msg));
await clientWebSocket.SendAsync(bytesToSend, WebSocketMessageType.Text, true, CancellationToken.None);websocket和socket
}
}
接收消息
          ArraySegment<byte> bytesReceived = new ArraySegment<byte>(new byte[1024]);
WebSocketReceiveResult result = await ws.ReceiveAsync(bytesReceived, CancellationToken.None);
Console.WriteLine(Encoding.UTF8.GetString(bytesReceived.Array, 0, result.Count));
ClientWebSocket⾥⾯的⽅法都是异步的,如果同步⽅法调⽤异步:
1.不需要获取返回值的:
clientWebSocket.ConnectAsync(serverUri, CancellationToken.None).Wait();
2.需要获取返回值的
var result = clientWebSocket.ConnectAsync(serverUri, CancellationToken.None).GetAwaiter().GetResult();
因为是引⽤dll发送给服务器的,当主线程关闭前⼀刻发送信息给服务器可能接收不到最后⾯那条数据,原因是链接已经关闭了,发送信息失败,为确保信息能接收可以定义结束命令,在发送结束命令后程序休眠两秒,或者全局定义,每次发送信息都休眠⼀会。
更新:代理问题
WebSocket客户端⼀般都是Web的JS,在控制台搞客户端最简单的⽅法是引⽤第三⽅的包,像WebSocket4Net,websocket-sharp等,⽤第三⽅的包越过代理可以直接在设置⾥⾯这样操作:
⽽如果⽤原⽣的ClientWebSocket的话上⾯的越过代理⽅式就不⾏了,即使设置了也会报403的错误:
System.AggregateException:“One or more errors occurred. (The server returned status code '403' when status code '101' was expected.)”
琢磨了⽼半天后⾯⽆意试⼀下:
clientWebSocket.Options.Proxy = null;
居然就连接成功了。
差点爆粗⼝;
⽰例:
static void Main(string[] args)
{
ClientWebSocket clientWebSocket = new ClientWebSocket();
var webSocketUrl = $@"ws://10.88.22.62:6008";
var serverUri = new Uri(webSocketUrl);
clientWebSocket.Options.Proxy = null;
clientWebSocket.ConnectAsync(serverUri, CancellationToken.None).Wait();
Console.ReadKey();
}
更新:ClientWebSocket不⽀持win7系统,由于要⽤到我去挖了第三⽅库的底层并将他们实现:

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。