WebSocket异步通讯,实时返回数据

时间:2022-02-13 06:41:10

第一种方式

// 服务端:
//var listener = new HttpListener();
// listener.Prefixes.Add("http://*:8080/");
//listener.Start();
//var context = await listener.GetContextAsync();
//var wsContext = await context.AcceptWebSocketAsync(null);
//var ws = wsContext.WebSocket;
// 客户端:
//var ws = new ClientWebSocket();
//await ws.ConnectAsync(new Uri("ws://127.0.0.1:8080"), CancellationToken.None);

#region MyRegion
// 1. 使用.NET4.5 自带的WebSocket
//服务端:
//var listener = new HttpListener();
// listener.Prefixes.Add("http://*:8080/");
//listener.Start();
//var context = await listener.GetContextAsync();
// var wsContext = await context.AcceptWebSocketAsync(null);
// var ws = wsContext.WebSocket;
// 客户端:
//var ws = new ClientWebSocket();
// await ws.ConnectAsync(new Uri("ws://127.0.0.1:8080"), CancellationToken.None);

//2. 使用 websocket-sharp dll提供的 WebSocket(支持.NET4.0)
//客户端:

//_caiNiaoWs = new WebSocket(WsUrl);
// _caiNiaoWs.OnMessage += (sender, e) => OnMessage(e.Data);
// _caiNiaoWs.Connect();

// 3. 使用 Socket 类(支持.NET4.0)

第二种方式

//int port = 1234;
//string host = "127.0.0.1";

//IPAddress ip = IPAddress.Parse(host);
//IPEndPoint ipe = new IPEndPoint(ip, port);

//Socket sSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//sSocket.Bind(ipe);
//sSocket.Listen(0);
//Console.WriteLine("监听已经打开,请等待");

////receive message
//Socket serverSocket = sSocket.Accept();
//Console.WriteLine("连接已经建立");
//string recStr = "";
//byte[] recByte = new byte[4096];
//int bytes = serverSocket.Receive(recByte, recByte.Length, 0);
//recStr += Encoding.ASCII.GetString(recByte, 0, bytes);

////send message
//Console.WriteLine("服务器端获得信息:{0}", recStr);
//string sendStr = "send to client :hello";
//byte[] sendByte = Encoding.ASCII.GetBytes(sendStr);
//serverSocket.Send(sendByte, sendByte.Length, 0);
//serverSocket.Close();
//sSocket.Close();

//int port = 1234;
//string host = "127.0.0.1";//服务器端ip地址

//IPAddress ip = IPAddress.Parse(host);
//IPEndPoint ipe = new IPEndPoint(ip, port);

// Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//clientSocket.Connect(ipe);

////send message
//string sendStr = "begin#70";
//byte[] sendBytes = Encoding.ASCII.GetBytes(sendStr);
//clientSocket.Send(sendBytes);

////receive message
//string recStr = "";
//byte[] recBytes = new byte[4096];
//int bytes = clientSocket.Receive(recBytes, recBytes.Length, 0);
//recStr += Encoding.ASCII.GetString(recBytes, 0, bytes);
//Console.WriteLine(recStr);

//clientSocket.Close();

实时响应

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Net.WebSockets;
using System.IO;

namespace WebSocketTest
{
public class Program
{
static void Main(string[] args)
{
Console.WriteLine("start....");

//4.0方式
string url = "ws://127.0.0.1:1234/";
try
{
ClientWebSocket cln = new ClientWebSocket();
cln.ConnectAsync(new Uri(url), new CancellationToken()).Wait();

byte[] bytess = Encoding.Default.GetBytes("begin#70");
cln.SendAsync(new ArraySegment<byte>(bytess), WebSocketMessageType.Text, true, new CancellationToken()).Wait();
byte[] bytes2 = new byte[1000 * 500];
//var webSocketReceiveResult = cln.ReceiveAsync(new ArraySegment<byte>(bytes2), CancellationToken.None);

Program.GG(cln);//异步方法,很关键,

//string xx = Encoding.Default.GetString(bytes2);
Console.WriteLine("11111111111");
Console.Read();

}
catch (Exception ex)
{
string ss = ex.ToString();
Console.WriteLine(ss);
//}
Console.Read();
}
}

public static async void GG(ClientWebSocket clientWebSocket)
{
ArraySegment<Byte> buffer = new ArraySegment<byte>(new Byte[8192]);

WebSocketReceiveResult result = null;

using (var ms = new MemoryStream())
{
do
{
result = await clientWebSocket.ReceiveAsync(buffer, CancellationToken.None);
//result = cln.ReceiveAsync(buffer, CancellationToken.None);
ms.Write(buffer.Array, buffer.Offset, result.Count);
}
while (!result.EndOfMessage);

ms.Seek(0, SeekOrigin.Begin);

if (result.MessageType == WebSocketMessageType.Text)
{
using (var reader = new StreamReader(ms, Encoding.UTF8))
{

// do stuff

string xx = reader.ReadToEnd();
Console.WriteLine(xx);
}
}
}
}

}

}