備忘録

備忘録

WebSocket4Net C# .NET Standard対応 WebSocket ライブラリ

Ⅰ. はじめに

WebSocket4Net は2017/05/11 時点でベータ段階ですが .NET Standard 対応の WebSocket ライブラリです。

Ⅱ. 使い方

1. 「プレリリースを含める」にチェックを入れる

2017/05/11 時点で .NET Standard 対応版がベータ段階なのでチェックを入れます。

2. 「WebSocket4Net」で検索し、インストールする

f:id:kagasu:20170511113556p:plain

3. サンプルプログラム
using System;
using WebSocket4Net;

namespace WebSocketSample
{
  class Program
  {
    static void Main(string[] args)
    {
      var websocket = new WebSocket("ws://example.com:81/...");

      websocket.Opened += Websocket_Opened;
      websocket.MessageReceived += Websocket_MessageReceived;
      websocket.Closed += Websocket_Closed;
      websocket.DataReceived += Websocket_DataReceived;
      websocket.Error += Websocket_Error;

      websocket.AutoSendPingInterval = 30;
      websocket.EnableAutoSendPing = true;

      websocket.Open();

      Console.ReadKey();
    }

    private void Websocket_Opened(object sender, EventArgs e)
    {
      Console.WriteLine("Websocket_Opened");
    }

    private static void Websocket_Error(object sender, SuperSocket.ClientEngine.ErrorEventArgs e)
    {
      Console.WriteLine("Websocket_Error");
    }

    private static void Websocket_DataReceived(object sender, DataReceivedEventArgs e)
    {
      Console.WriteLine($"Websocket_DataReceived { e.Data }");
    }

    private static void Websocket_Closed(object sender, EventArgs e)
    {
      Console.WriteLine("closed");
    }

    private static void Websocket_MessageReceived(object sender, MessageReceivedEventArgs e)
    {
      Console.WriteLine($"Websocket_MessageReceived { e.Message }");
    }
  }
}