zoukankan      html  css  js  c++  java
  • 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);

    #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);
    }
    }
    }
    }

    }

    }

  • 相关阅读:
    轻松搭建CAS 5.x系列(7)-在CAS Server使用第三方帐号做认证
    轻松搭建CAS 5.x系列(6)-在CAS Server上增加OAuth2.0协议
    轻松搭建CAS 5.x系列(5)-增加密码找回和密码修改功能
    CAS 5.x搭建常见问题系列(3).Failure to find org.apereo.cas:cas-server-support-pm-jdbc:jar:5.1.9
    CAS 5.x搭建常见问题系列(2).PKIX path building failed
    CAS 5.x搭建常见问题系列(1).未认证的授权服务
    轻松搭建CAS 5.x系列(4)-Java客户端程序接入CAS单点登录,Hello World版
    轻松搭建CAS 5.x系列文章
    CAS实现SSO单点登录-CAS Server 5.3搭建 cas5.3搭建 cas5.3去除https cas 去除https cas 5.x 去除https
    互联网大咖都要收藏的几个网站,纯干货
  • 原文地址:https://www.cnblogs.com/1175429393wljblog/p/9887805.html
Copyright © 2011-2022 走看看