Skip to content

Commit f0cc428

Browse files
committed
maintain ping pong in router
1 parent dc8b582 commit f0cc428

File tree

10 files changed

+174
-87
lines changed

10 files changed

+174
-87
lines changed

src/SocketIOClient.Sample/Program.cs

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,8 @@ static async Task Main(string[] args)
2222
{
2323
{"token", "V2" }
2424
},
25-
AutoUpgrade = false
25+
AutoUpgrade = false,
26+
EIO = 3
2627
});
2728

2829
socket.OnConnected += Socket_OnConnected;
@@ -68,8 +69,8 @@ private static async void Socket_OnConnected(object sender, EventArgs e)
6869
//while (true)
6970
//{
7071
// await Task.Delay(1000);
71-
//await socket.EmitAsync("hi", DateTime.Now.ToShortDateString());
72-
await socket.EmitAsync("welcome");
72+
await socket.EmitAsync("hi", DateTime.Now.ToShortDateString());
73+
//await socket.EmitAsync("welcome");
7374
//}
7475
//byte[] bytes = Encoding.UTF8.GetBytes("ClientCallsServerCallback_1Params_0");
7576
//await socket.EmitAsync("client calls the server's callback 1", bytes);

src/SocketIOClient.UnitTest/TransportTests/HttpTransportTest.cs

Lines changed: 32 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -29,12 +29,12 @@ public async Task TextWithBinaryTest()
2929

3030
var uriConverter = new Mock<IUriConverter>();
3131
uriConverter
32-
.Setup(x => x.GetHandshakeUri(It.IsAny<Uri>(), It.IsAny<string>(), It.IsAny<IEnumerable<KeyValuePair<string, string>>>()))
32+
.Setup(x => x.GetHandshakeUri(It.IsAny<Uri>(), It.IsAny<int>(), It.IsAny<string>(), It.IsAny<IEnumerable<KeyValuePair<string, string>>>()))
3333
.Returns(new Uri(uri));
3434

3535
string resultText = null;
3636
var bytes = new List<byte[]>();
37-
var transport = new HttpTransport(httpClient)
37+
var transport = new HttpTransport(httpClient, 4)
3838
{
3939
OnTextReceived = text => resultText = text,
4040
OnBinaryReceived = b => bytes.Add(b)
@@ -70,5 +70,35 @@ public async Task TextWithBinaryTest()
7070
Assert.AreEqual(0, c1);
7171
Assert.AreEqual(0, c2);
7272
}
73+
74+
[TestMethod]
75+
public async Task Eio3HttpConnectedTest()
76+
{
77+
string uri = "http://localhost:11002/socket.io/?token=V3&EIO=3&transport=polling";
78+
79+
var mockHttp = new MockHttpMessageHandler();
80+
mockHttp.When(uri)
81+
.Respond("text/plain", "2:40");
82+
var httpClient = mockHttp.ToHttpClient();
83+
84+
var clientWebSocket = new Mock<IClientWebSocket>();
85+
86+
var uriConverter = new Mock<IUriConverter>();
87+
uriConverter
88+
.Setup(x => x.GetHandshakeUri(It.IsAny<Uri>(), It.IsAny<int>(), It.IsAny<string>(), It.IsAny<IEnumerable<KeyValuePair<string, string>>>()))
89+
.Returns(new Uri(uri));
90+
91+
var result = new List<string>();
92+
var transport = new HttpTransport(httpClient, 3)
93+
{
94+
OnTextReceived = text => result.Add(text)
95+
};
96+
await transport.GetAsync(uri, CancellationToken.None);
97+
98+
await Task.Delay(100);
99+
100+
Assert.AreEqual(1, result.Count);
101+
Assert.AreEqual("40", result[0]);
102+
}
73103
}
74104
}

src/SocketIOClient.UnitTest/UriConverterTest.cs

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ public void GetHandshakeUriWithHttp()
2121
{
2222
new KeyValuePair<string, string>("token", "test")
2323
};
24-
var result = cvt.GetHandshakeUri(serverUri, string.Empty, kvs);
24+
var result = cvt.GetHandshakeUri(serverUri, 4, string.Empty, kvs);
2525
Assert.AreEqual("http://localhost/socket.io/?EIO=4&transport=polling&token=test", result.ToString());
2626
}
2727

@@ -35,7 +35,7 @@ public void GetHandshakeUriWithHttp80()
3535
{
3636
new KeyValuePair<string, string>("token", "test")
3737
};
38-
var result = cvt.GetHandshakeUri(serverUri, string.Empty, kvs);
38+
var result = cvt.GetHandshakeUri(serverUri, 4, string.Empty, kvs);
3939
Assert.AreEqual("http://localhost/socket.io/?EIO=4&transport=polling&token=test", result.ToString());
4040
}
4141

@@ -49,7 +49,7 @@ public void GetHandshakeUriWithHttps443()
4949
{
5050
new KeyValuePair<string, string>("token", "test")
5151
};
52-
var result = cvt.GetHandshakeUri(serverUri, "/sio", kvs);
52+
var result = cvt.GetHandshakeUri(serverUri, 4, "/sio", kvs);
5353
Assert.AreEqual("https://localhost/sio/?EIO=4&transport=polling&token=test", result.ToString());
5454
}
5555

@@ -60,7 +60,7 @@ public void GetHandshakeUriWithWs80()
6060

6161
var serverUri = new Uri("ws://localhost:80");
6262
var kvs = new List<KeyValuePair<string, string>>();
63-
var result = cvt.GetHandshakeUri(serverUri, string.Empty, kvs);
63+
var result = cvt.GetHandshakeUri(serverUri, 4, string.Empty, kvs);
6464
Assert.AreEqual("http://localhost/socket.io/?EIO=4&transport=polling", result.ToString());
6565
}
6666

@@ -74,7 +74,7 @@ public void GetHandshakeUriWithWss443()
7474
{
7575
new KeyValuePair<string, string>("token", "test")
7676
};
77-
var result = cvt.GetHandshakeUri(serverUri, string.Empty, kvs);
77+
var result = cvt.GetHandshakeUri(serverUri, 4, string.Empty, kvs);
7878
Assert.AreEqual("https://localhost/socket.io/?EIO=4&transport=polling&token=test", result.ToString());
7979
}
8080

@@ -88,7 +88,7 @@ public void GetHandshakeUriWithHttps80()
8888
{
8989
new KeyValuePair<string, string>("token", "test")
9090
};
91-
var result = cvt.GetHandshakeUri(serverUri, string.Empty, kvs);
91+
var result = cvt.GetHandshakeUri(serverUri, 4, string.Empty, kvs);
9292
Assert.AreEqual("https://localhost:80/socket.io/?EIO=4&transport=polling&token=test", result.ToString());
9393
}
9494
}

src/SocketIOClient/Messages/PongMessage.cs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
using SocketIOClient.Transport;
2+
using System;
23
using System.Collections.Generic;
34

45
namespace SocketIOClient.Messages
@@ -17,6 +18,8 @@ public class PongMessage : IMessage
1718

1819
public TransportProtocol Protocol { get; set; }
1920

21+
public TimeSpan Duration { get; set; }
22+
2023
public void Read(string msg)
2124
{
2225
}

src/SocketIOClient/SocketIO.cs

Lines changed: 5 additions & 54 deletions
Original file line numberDiff line numberDiff line change
@@ -104,10 +104,6 @@ public Uri ServerUri
104104
Dictionary<string, Action<SocketIOResponse>> _eventHandlers;
105105
CancellationTokenSource _connectionTokenSorce;
106106
double _reconnectionDelay;
107-
CancellationTokenSource _pingTokenSource;
108-
CancellationToken _pingToken;
109-
DateTime _pingTime;
110-
111107

112108
#region Socket.IO event
113109
public event EventHandler OnConnected;
@@ -237,25 +233,14 @@ public async Task ConnectAsync()
237233
}
238234
}
239235

240-
private async void PingHandler()
236+
private void PingHandler()
241237
{
242-
try
243-
{
244-
OnPing?.Invoke(this, EventArgs.Empty);
245-
DateTime pingTime = DateTime.Now;
246-
await Router.SendAsync(new PongMessage(), CancellationToken.None).ConfigureAwait(false);
247-
OnPong?.Invoke(this, DateTime.Now - pingTime);
248-
}
249-
catch (Exception e)
250-
{
251-
Debug.WriteLine(e);
252-
InvokeDisconnect(DisconnectReason.PingTimeout);
253-
}
238+
OnPing?.Invoke(this, EventArgs.Empty);
254239
}
255240

256-
private void PongHandler()
241+
private void PongHandler(PongMessage msg)
257242
{
258-
OnPong?.Invoke(this, DateTime.Now - _pingTime);
243+
OnPong?.Invoke(this, msg.Duration);
259244
}
260245

261246
private void ConnectedHandler(ConnectedMessage msg)
@@ -268,34 +253,6 @@ private void ConnectedHandler(ConnectedMessage msg)
268253
OnReconnected?.Invoke(this, Attempts);
269254
}
270255
Attempts = 0;
271-
if (Router.Eio == 3)
272-
{
273-
if (_pingTokenSource != null)
274-
{
275-
_pingTokenSource.Cancel();
276-
_pingTokenSource = new CancellationTokenSource();
277-
_pingToken = _pingTokenSource.Token;
278-
}
279-
Task.Factory.StartNew(PingAsync, TaskCreationOptions.LongRunning);
280-
}
281-
}
282-
283-
private async Task PingAsync()
284-
{
285-
while (!_pingToken.IsCancellationRequested)
286-
{
287-
await Task.Delay(Router.PingInterval);
288-
try
289-
{
290-
await Router.SendAsync(new PingMessage(), CancellationToken.None).ConfigureAwait(false);
291-
_pingTime = DateTime.Now;
292-
OnPing?.Invoke(this, EventArgs.Empty);
293-
}
294-
catch
295-
{
296-
InvokeDisconnect(DisconnectReason.PingTimeout);
297-
}
298-
}
299256
}
300257

301258
private void DisconnectedHandler()
@@ -404,7 +361,7 @@ private void OnMessageReceived(IMessage msg)
404361
PingHandler();
405362
break;
406363
case MessageType.Pong:
407-
PongHandler();
364+
PongHandler(msg as PongMessage);
408365
break;
409366
case MessageType.Connected:
410367
ConnectedHandler(msg as ConnectedMessage);
@@ -660,7 +617,6 @@ private async void InvokeDisconnect(string reason)
660617
{
661618
Connected = false;
662619
OnDisconnected?.Invoke(this, reason);
663-
_pingTokenSource?.Cancel();
664620
try
665621
{
666622
await Router.DisconnectAsync();
@@ -697,11 +653,6 @@ public void Dispose()
697653
_eventHandlers.Clear();
698654
_connectionTokenSorce.Cancel();
699655
_connectionTokenSorce.Dispose();
700-
if (_pingTokenSource != null)
701-
{
702-
_pingTokenSource.Cancel();
703-
_pingTokenSource.Dispose();
704-
}
705656
}
706657
}
707658
}

src/SocketIOClient/SocketIOOptions.cs

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

2021
public string Path { get; set; }
@@ -52,5 +53,7 @@ public double RandomizationFactor
5253
public Dictionary<string, string> ExtraHeaders { get; set; }
5354

5455
public bool AutoUpgrade { get; set; }
56+
57+
public int EIO { get; set; }
5558
}
5659
}

src/SocketIOClient/Transport/HttpTransport.cs

Lines changed: 37 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -9,12 +9,14 @@ namespace SocketIOClient.Transport
99
{
1010
public class HttpTransport : IReceivable
1111
{
12-
public HttpTransport(HttpClient httpClient)
12+
public HttpTransport(HttpClient httpClient, int eio)
1313
{
1414
_client = httpClient;
15+
_eio = eio;
1516
}
1617

1718
readonly HttpClient _client;
19+
readonly int _eio;
1820

1921
public Action<string> OnTextReceived { get; set; }
2022
public Action<byte[]> OnBinaryReceived { get; set; }
@@ -62,17 +64,44 @@ public async Task PostAsync(string uri, IEnumerable<byte[]> bytes, CancellationT
6264

6365
private void Produce(string text)
6466
{
65-
string[] items = text.Split(new[] { '' }, StringSplitOptions.RemoveEmptyEntries);
66-
foreach (var item in items)
67+
if (_eio == 3)
6768
{
68-
if (item[0] == 'b')
69+
while (true)
6970
{
70-
byte[] bytes = Convert.FromBase64String(item.Substring(1));
71-
OnBinaryReceived(bytes);
71+
int index = text.IndexOf(':');
72+
if (index == -1)
73+
{
74+
break;
75+
}
76+
if (int.TryParse(text.Substring(0, index), out int length))
77+
{
78+
string msg = text.Substring(index + 1, length);
79+
OnTextReceived(msg);
80+
if (index + length + 1 > text.Length - 1)
81+
{
82+
break;
83+
}
84+
}
85+
else
86+
{// 这里有问题,F5 启动 Sample 测试
87+
break;
88+
}
7289
}
73-
else
90+
}
91+
else
92+
{
93+
string[] items = text.Split(new[] { '' }, StringSplitOptions.RemoveEmptyEntries);
94+
foreach (var item in items)
7495
{
75-
OnTextReceived(item);
96+
if (item[0] == 'b')
97+
{
98+
byte[] bytes = Convert.FromBase64String(item.Substring(1));
99+
OnBinaryReceived(bytes);
100+
}
101+
else
102+
{
103+
OnTextReceived(item);
104+
}
76105
}
77106
}
78107
}

0 commit comments

Comments
 (0)