• 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
    }
    }

  • 相关阅读:
    数组中找出最小的K个数
    温故而知新---Java(一)
    写一手简洁的代码
    同步IO与同步非阻塞IO的理解
    旋转打印矩阵
    求仅出现一次的最早字符
    spring 自定义schema 加载异常 White spaces are required between publicId and systemId.
    Java位运算知识点整理
    Idea 插件开发之DubboInvoke实践
    pinpoint插件开发实践
  • 原文地址:https://www.cnblogs.com/1175429393wljblog/p/9887750.html
Copyright © 2020-2023  润新知