操作系统Windows8或以上
using
System;
using
System.Net.WebSockets;
using
System.Text;
using
System.Threading;
class
Client
{
static
void
Main(
string
[] args)
{
var client =
new
ClientWebSocket();
client.ConnectAsync(
new
Uri(
"ws://echo.websocket.org"
), CancellationToken.None).Wait();
//client.ConnectAsync(new Uri("ws://localhost:4567/ws/"), CancellationToken.None).Wait();
StartReceiving(client);
string
line;
while
((line = Console.ReadLine()) !=
"exit"
)
{
var array =
new
ArraySegment<
byte
>(Encoding.UTF8.GetBytes(line));
client.SendAsync(array, WebSocketMessageType.Text,
true
, CancellationToken.None);
}
}
static
async
void
StartReceiving(ClientWebSocket client)
{
while
(
true
)
{
var array =
new
byte
[4096];
var result = await client.ReceiveAsync(
new
ArraySegment<
byte
>(array), CancellationToken.None);
if
(result.MessageType == WebSocketMessageType.Text)
{
string
msg = Encoding.UTF8.GetString(array, 0, result.Count);
Console.ForegroundColor = ConsoleColor.DarkBlue;
Console.WriteLine(
"--> {0}"
, msg);
Console.ForegroundColor = ConsoleColor.DarkGray;
}
}
}
}
一、调用ConnectAsync进行连接(感谢例子中使用的websocket.org的免费回声服务)。
二、用ReceiveAsync进行接收,用SendAsync进行发送。
DotNet的WebSocket依赖于底层的http.sys。因此需要操作系统Win8或以上的支持 。
如果你要在Win7等系统上用,则要自己用Socket做,或者用第三方的类库。
#region ClientWebSocket
readonly ClientWebSocket _webSocket = new ClientWebSocket();
readonly CancellationToken _cancellation = new CancellationToken();
public async void WebSocket() {
try {
//建立连接
var url = "ws://121.40.165.18:8800";
await _webSocket.ConnectAsync(new Uri(url), _cancellation);
var bsend = new byte[1024];
await _webSocket.SendAsync(new ArraySegment<byte>(bsend), WebSocketMessageType.Binary, true, _cancellation); //发送数据
while (true) {
var result = new byte[1024];
await _webSocket.ReceiveAsync(new ArraySegment<byte>(result), new CancellationToken());//接受数据
var lastbyte = ByteCut(result, 0x00);
var str = Encoding.UTF8.GetString(lastbyte, 0, lastbyte.Length);
}
} catch (Exception ex) {
Console.WriteLine(ex.Message);
}
}
#endregion
我目前正在研究使用websockets来在客户端/代理和服务器之间进行通信,并决定为此目的查看C#.虽然我之前使用过Websockets和C#,但这是我第一次使用两者.第一次尝试使用以下指南:
http://www.codeproject.com/Articles/618032/Using-WebSocket-in-NET-Part
public static void Main(string[] args)
{
Task t = Echo();
t.Wait();
}
private static async Task Echo()
{
using (ClientWebSocket ws = new ClientWebSocket())
{
Uri serverUri = new Uri("ws://localhost:49889/");
await ws.ConnectAsync(serverUri, CancellationToken.None);
while (ws.State == WebSocketState.Open)
{
Console.Write("Input message ('exit' to exit): ");
string msg = Console.ReadLine();
if (msg == "exit")
{
break;
}
ArraySegment bytesToSend = new ArraySegment(Encoding.UTF8.GetBytes(msg));
await ws.SendAsync(bytesToSend, WebSocketMessageType.Text, true, CancellationToken.None);
ArraySegment bytesReceived = new ArraySegment(new byte[1024]);
WebSocketReceiveResult result = await ws.ReceiveAsync(bytesReceived, CancellationToken.None);
Console.WriteLine(Encoding.UTF8.GetString(bytesReceived.Array, 0, result.Count));
}
}
}
虽然这似乎是按预期的方式工作,但我想知道是否有任何方法可以使用ClientWebSocket中的.NET内置流/读取器?
似乎对我来说,微软拥有丰富的成熟的流和阅读器类集,但随后决定实现ClientWebSocket,只能读取必须手动处理的字节块.
让我说我想传输xml,我很容易将套接字流包装在一个XmlTextReader中,但是这并不是ClientWebSocket显而易见的.