WebSocketTest 非同步通訊,實時返回資料
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....");
//var server = new WebSocet();
//server.StartAccept(socket =>
// {
// socket.OnOpen = () => Console.WriteLine("Open!");
// socket.OnClose = () => Console.WriteLine("Close!");
// socket.OnMessage = message => socket.Send(message);
// });
//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();
////服務端:
//var listener = new HttpListener();
//listener.Prefixes.Add("http://*:8080/");
//listener.Start();
//var context = listener.GetContextAsync();
//var wsContext = context.Result.AcceptWebSocketAsync("");
//var ws = wsContext.Result.WebSocket;
////客戶端:
//var cln = new ClientWebSocket();
//cln.ConnectAsync(new Uri("ws://127.0.0.1:8080"), CancellationToken.None);
//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);
//webSocketReceiveResult.GetAwaiter().GetResult();
//Thread.Sleep(10000);
//if (webSocketReceiveResult.IsCompleted)
//{
// //Console.WriteLine(webSocketReceiveResult.Result.));
// string xx = Encoding.GetEncoding("utf-8").GetString(bytes2, 0, webSocketReceiveResult.Result.Count);
// Console.WriteLine(xx);
//}
//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);
}
}
}
}
// 服務端:
//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)
//http://blog.csdn.net/qq_29701359/article/details/53130050
#endregion
}
}