-
Notifications
You must be signed in to change notification settings - Fork 45
/
Copy pathWebsocket.cs
106 lines (102 loc) · 2.86 KB
/
Websocket.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
using System;
using System.Threading.Tasks;
using System.Threading;
using WebSocket4Net;
using System.Diagnostics;
using System.Collections.Generic;
namespace MixchSitePlugin
{
class Websocket
{
public event EventHandler Opened;
public event EventHandler<string> Received;
WebSocket _ws;
private void Log(string str)
{
Debug.Write(DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"));
Debug.WriteLine(str);
}
public Task ReceiveAsync(string url, string userAgent, string origin)
{
if (_ws != null)
throw new InvalidOperationException("_ws is not null");
var tcs = new TaskCompletionSource<object>();
var subProtocol = "";
_ws = new WebSocket4Net.WebSocket(url, subProtocol, null, null, userAgent, origin, WebSocket4Net.WebSocketVersion.Rfc6455)
{
EnableAutoSendPing = false,
AutoSendPingInterval = 0,
ReceiveBufferSize = 8192,
NoDelay = true
};
_ws.MessageReceived += (s, e) =>
{
Log("_ws.MessageReceived: " + e.Message);
Received?.Invoke(this, e.Message);
};
_ws.DataReceived += (s, e) =>
{
Debug.WriteLine("DataReceived");
};
_ws.Opened += (s, e) =>
{
Log("_ws.Opened");
Opened?.Invoke(this, EventArgs.Empty);
};
_ws.Closed += (s, e) =>
{
Log("_ws.Closed");
try
{
tcs.TrySetResult(null);
}
finally
{
if (_ws != null)
{
_ws.Dispose();
_ws = null;
}
}
};
_ws.Error += (s, e) =>
{
Log("_ws.Error");
try
{
tcs.SetException(e.Exception);
}
finally
{
if (_ws != null)
{
_ws.Dispose();
_ws = null;
}
}
};
_ws.Open();
return tcs.Task;
}
public async Task SendAsync(string str)
{
await Task.Yield();
if (_ws != null)
{
_ws.Send(str);
Debug.WriteLine("websocket send:" + str);
}
await Task.CompletedTask;
}
public void Disconnect()
{
if (_ws != null)
{
_ws.Close();
}
}
public Websocket()
{
}
}
}