Skip to content

Commit b1ff8e2

Browse files
committed
eio 2 polling binary
1 parent f0cc428 commit b1ff8e2

File tree

5 files changed

+131
-50
lines changed

5 files changed

+131
-50
lines changed

src/SocketIOClient.UnitTest/TransportTests/HttpTransportTest.cs

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@
66
using System;
77
using System.Collections.Generic;
88
using System.Globalization;
9+
using System.Net.Http;
10+
using System.Net.Http.Headers;
911
using System.Text;
1012
using System.Threading;
1113
using System.Threading.Tasks;
@@ -100,5 +102,48 @@ public async Task Eio3HttpConnectedTest()
100102
Assert.AreEqual(1, result.Count);
101103
Assert.AreEqual("40", result[0]);
102104
}
105+
106+
[TestMethod]
107+
public async Task Eio3HttpBinaryTest()
108+
{
109+
string uri = "http://localhost:11002/socket.io/?token=V3&EIO=3&transport=polling";
110+
byte[] arrOutput = { 0x00, 0x07, 0x05, 0xFF, 0x34, 0x35, 0x32, 0x2D, 0x5B, 0x22, 0x77, 0x65, 0x6C, 0x63, 0x6F, 0x6D, 0x65, 0x22, 0x2C, 0x7B, 0x22, 0x5F, 0x70, 0x6C, 0x61, 0x63, 0x65, 0x68, 0x6F, 0x6C, 0x64, 0x65, 0x72, 0x22, 0x3A, 0x74, 0x72, 0x75, 0x65, 0x2C, 0x22, 0x6E, 0x75, 0x6D, 0x22, 0x3A, 0x30, 0x7D, 0x2C, 0x7B, 0x22, 0x5F, 0x70, 0x6C, 0x61, 0x63, 0x65, 0x68, 0x6F, 0x6C, 0x64, 0x65, 0x72, 0x22, 0x3A, 0x74, 0x72, 0x75, 0x65, 0x2C, 0x22, 0x6E, 0x75, 0x6D, 0x22, 0x3A, 0x31, 0x7D, 0x5D, 0x01, 0x02, 0x09, 0xFF, 0x04, 0x77, 0x65, 0x6C, 0x63, 0x6F, 0x6D, 0x65, 0x20, 0x42, 0x71, 0x46, 0x63, 0x32, 0x53, 0x6F, 0x72, 0x67, 0x75, 0x6B, 0x4F, 0x32, 0x36, 0x2D, 0x6C, 0x41, 0x41, 0x41, 0x4A, 0x01, 0x05, 0xFF, 0x04, 0x74, 0x65, 0x73, 0x74 };
111+
var mockHttp = new MockHttpMessageHandler();
112+
mockHttp.When(uri)
113+
.Respond(req =>
114+
{
115+
var content = new ByteArrayContent(arrOutput);
116+
content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
117+
return new HttpResponseMessage
118+
{
119+
Content = content
120+
};
121+
});
122+
var httpClient = mockHttp.ToHttpClient();
123+
124+
var clientWebSocket = new Mock<IClientWebSocket>();
125+
126+
var uriConverter = new Mock<IUriConverter>();
127+
uriConverter
128+
.Setup(x => x.GetHandshakeUri(It.IsAny<Uri>(), It.IsAny<int>(), It.IsAny<string>(), It.IsAny<IEnumerable<KeyValuePair<string, string>>>()))
129+
.Returns(new Uri(uri));
130+
131+
var texts = new List<string>();
132+
var bytes = new List<byte[]>();
133+
var transport = new HttpTransport(httpClient, 3)
134+
{
135+
OnTextReceived = text => texts.Add(text),
136+
OnBinaryReceived = b => bytes.Add(b)
137+
};
138+
await transport.GetAsync(uri, CancellationToken.None);
139+
140+
await Task.Delay(100);
141+
142+
Assert.AreEqual(1, texts.Count);
143+
Assert.AreEqual("452-[\"welcome\",{\"_placeholder\":true,\"num\":0},{\"_placeholder\":true,\"num\":1}]", texts[0]);
144+
Assert.AreEqual(2, bytes.Count);
145+
Assert.AreEqual("welcome BqFc2SorgukO26-lAAAJ", Encoding.UTF8.GetString(bytes[0]));
146+
Assert.AreEqual("test", Encoding.UTF8.GetString(bytes[1]));
147+
}
103148
}
104149
}

src/SocketIOClient/Messages/ConnectedMessage.cs

Lines changed: 0 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -42,10 +42,6 @@ public string Write()
4242
{
4343
if (Eio == 3)
4444
{
45-
if (Protocol == TransportProtocol.Polling)
46-
{
47-
return Eio3PollingWrite();
48-
}
4945
return Eio3Write();
5046
}
5147
return Eio4Write();
@@ -126,11 +122,5 @@ public string Eio3Write()
126122
builder.Append(',');
127123
return builder.ToString();
128124
}
129-
130-
public string Eio3PollingWrite()
131-
{
132-
string message = Eio3Write();
133-
return message.Length + ":" + message;
134-
}
135125
}
136126
}

src/SocketIOClient/SocketIOOptions.cs

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,6 @@ public SocketIOOptions()
1515
ConnectionTimeout = TimeSpan.FromSeconds(20);
1616
Reconnection = true;
1717
AutoUpgrade = true;
18-
EIO = 4;
1918
}
2019

2120
public string Path { get; set; }
@@ -53,7 +52,5 @@ public double RandomizationFactor
5352
public Dictionary<string, string> ExtraHeaders { get; set; }
5453

5554
public bool AutoUpgrade { get; set; }
56-
57-
public int EIO { get; set; }
5855
}
5956
}

src/SocketIOClient/Transport/HttpTransport.cs

Lines changed: 49 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -34,16 +34,14 @@ public async Task GetAsync(string uri, CancellationToken cancellationToken)
3434
{
3535
throw new HttpRequestException($"Response status code does not indicate success: {resMsg.StatusCode}");
3636
}
37-
string text = await resMsg.Content.ReadAsStringAsync().ConfigureAwait(false);
38-
Produce(text);
37+
await ProduceMessageAsync(resMsg).ConfigureAwait(false);
3938
}
4039

4140
public async Task PostAsync(string uri, string content, CancellationToken cancellationToken)
4241
{
4342
var httpContent = new StringContent(content);
4443
var resMsg = await _client.PostAsync(AppendRandom(uri), httpContent, cancellationToken).ConfigureAwait(false);
45-
string text = await resMsg.Content.ReadAsStringAsync().ConfigureAwait(false);
46-
Produce(text);
44+
await ProduceMessageAsync(resMsg).ConfigureAwait(false);
4745
}
4846

4947
public async Task PostAsync(string uri, IEnumerable<byte[]> bytes, CancellationToken cancellationToken)
@@ -62,7 +60,21 @@ public async Task PostAsync(string uri, IEnumerable<byte[]> bytes, CancellationT
6260
await PostAsync(uri, text, cancellationToken);
6361
}
6462

65-
private void Produce(string text)
63+
private async Task ProduceMessageAsync(HttpResponseMessage resMsg)
64+
{
65+
if (resMsg.Content.Headers.ContentType.MediaType == "application/octet-stream")
66+
{
67+
byte[] bytes = await resMsg.Content.ReadAsByteArrayAsync().ConfigureAwait(false);
68+
ProduceBytes(bytes);
69+
}
70+
else
71+
{
72+
string text = await resMsg.Content.ReadAsStringAsync().ConfigureAwait(false);
73+
ProduceText(text);
74+
}
75+
}
76+
77+
private void ProduceText(string text)
6678
{
6779
if (_eio == 3)
6880
{
@@ -83,7 +95,7 @@ private void Produce(string text)
8395
}
8496
}
8597
else
86-
{// 这里有问题,F5 启动 Sample 测试
98+
{
8799
break;
88100
}
89101
}
@@ -105,5 +117,36 @@ private void Produce(string text)
105117
}
106118
}
107119
}
120+
121+
private void ProduceBytes(byte[] bytes)
122+
{
123+
int i = 0;
124+
while (bytes.Length > i + 4)
125+
{
126+
byte type = bytes[i];
127+
var builder = new StringBuilder();
128+
i++;
129+
while (bytes[i] != byte.MaxValue)
130+
{
131+
builder.Append(bytes[i]);
132+
i++;
133+
}
134+
i++;
135+
int length = int.Parse(builder.ToString());
136+
if (type == 0)
137+
{
138+
var buffer = new byte[length];
139+
Buffer.BlockCopy(bytes, i, buffer, 0, buffer.Length);
140+
OnTextReceived(Encoding.UTF8.GetString(buffer));
141+
}
142+
else if (type == 1)
143+
{
144+
var buffer = new byte[length - 1];
145+
Buffer.BlockCopy(bytes, i + 1, buffer, 0, buffer.Length);
146+
OnBinaryReceived(buffer);
147+
}
148+
i += length;
149+
}
150+
}
108151
}
109152
}

src/SocketIOClient/Transport/TransportRouter.cs

Lines changed: 37 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -55,12 +55,12 @@ public TransportRouter(HttpClient httpClient, Func<IClientWebSocket> clientWebSo
5555

5656
public async Task ConnectAsync()
5757
{
58-
Eio = _options.EIO;
58+
//Eio = _options.EIO;
5959
if (_webSocketTransport != null)
6060
{
6161
_webSocketTransport.Dispose();
6262
}
63-
Uri uri = UriConverter.GetHandshakeUri(ServerUri, Eio, _options.Path, _options.Query);
63+
Uri uri = UriConverter.GetHandshakeUri(ServerUri, 3, _options.Path, _options.Query);
6464

6565
var req = new HttpRequestMessage(HttpMethod.Get, uri);
6666
SetHeaders(req);
@@ -74,6 +74,8 @@ public async Task ConnectAsync()
7474
var openedMessage = MessageFactory.CreateOpenedMessage(text);
7575

7676
Sid = openedMessage.Sid;
77+
Eio = openedMessage.Eio;
78+
uri = UriConverter.GetHandshakeUri(ServerUri, Eio, _options.Path, _options.Query);
7779
_ingInterval = openedMessage.PingInterval;
7880
if (openedMessage.Upgrades.Contains("websocket") && _options.AutoUpgrade)
7981
{
@@ -107,7 +109,7 @@ private void SetHeaders(HttpRequestMessage req)
107109

108110
private async Task WebSocketConnectAsync()
109111
{
110-
Uri uri = UriConverter.GetWebSocketUri(ServerUri, _options.EIO, _options.Path, _options.Query, Sid);
112+
Uri uri = UriConverter.GetWebSocketUri(ServerUri, Eio, _options.Path, _options.Query, Sid);
111113
await _webSocketTransport.ConnectAsync(uri).ConfigureAwait(false);
112114
_webSocketTransport.OnTextReceived = OnWebSocketTextReceived;
113115
_webSocketTransport.OnBinaryReceived = OnBinaryReceived;
@@ -163,13 +165,10 @@ private async Task PingAsync()
163165
await Task.Delay(_ingInterval);
164166
try
165167
{
166-
await SendAsync(new PingMessage(), CancellationToken.None).ConfigureAwait(false);
168+
var ping = new PingMessage();
169+
await SendAsync(ping, CancellationToken.None).ConfigureAwait(false);
167170
_pingTime = DateTime.Now;
168-
OnMessageReceived(new PingMessage
169-
{
170-
Eio = Eio,
171-
Protocol = Protocol
172-
});
171+
OnMessageReceived(ping);
173172
}
174173
catch
175174
{
@@ -192,6 +191,7 @@ private async void OnWebSocketTextReceived(string text)
192191
var msg = new ConnectedMessage
193192
{
194193
Namespace = Namespace,
194+
Eio = Eio,
195195
Sid = Sid,
196196
Protocol = TransportProtocol.WebSocket,
197197
Query = _options.Query
@@ -217,6 +217,30 @@ private async void OnTextReceived(string text)
217217
}
218218
else
219219
{
220+
if (Eio == 3)
221+
{
222+
if (msg.Type == MessageType.Connected)
223+
{
224+
var connectMsg = msg as ConnectedMessage;
225+
connectMsg.Sid = Sid;
226+
if ((string.IsNullOrEmpty(Namespace) && string.IsNullOrEmpty(connectMsg.Namespace)) || connectMsg.Namespace == Namespace)
227+
{
228+
if (_pingTokenSource != null)
229+
{
230+
_pingTokenSource.Cancel();
231+
_pingTokenSource = new CancellationTokenSource();
232+
_pingToken = _pingTokenSource.Token;
233+
}
234+
_ = Task.Factory.StartNew(PingAsync, TaskCreationOptions.LongRunning);
235+
}
236+
}
237+
else if (msg.Type == MessageType.Pong)
238+
{
239+
var pong = msg as PongMessage;
240+
pong.Duration = DateTime.Now - _pingTime;
241+
}
242+
}
243+
220244
OnMessageReceived(msg);
221245
if (msg.Type == MessageType.Ping)
222246
{
@@ -241,28 +265,6 @@ await SendAsync(new PongMessage
241265
OnTransportClosed();
242266
}
243267
}
244-
else if (msg.Type == MessageType.Pong)
245-
{
246-
var pong = msg as PongMessage;
247-
pong.Duration = DateTime.Now - _pingTime;
248-
}
249-
else if (msg.Type == MessageType.Connected)
250-
{
251-
var connectMsg = msg as ConnectedMessage;
252-
if ((string.IsNullOrEmpty(Namespace) && string.IsNullOrEmpty(connectMsg.Namespace)) || connectMsg.Namespace == Namespace)
253-
{
254-
if (Eio == 3)
255-
{
256-
if (_pingTokenSource != null)
257-
{
258-
_pingTokenSource.Cancel();
259-
_pingTokenSource = new CancellationTokenSource();
260-
_pingToken = _pingTokenSource.Token;
261-
}
262-
_ = Task.Factory.StartNew(PingAsync, TaskCreationOptions.LongRunning);
263-
}
264-
}
265-
}
266268
}
267269
}
268270
}
@@ -323,6 +325,10 @@ private async Task SendAsync(string text, CancellationToken cancellationToken)
323325
{
324326
if (Protocol == TransportProtocol.Polling)
325327
{
328+
if (Eio == 3)
329+
{
330+
text = text.Length + ":" + text;
331+
}
326332
await _httpTransport.PostAsync(_httpUri, text, cancellationToken).ConfigureAwait(false);
327333
}
328334
else

0 commit comments

Comments
 (0)