Skip to content

Commit cb13093

Browse files
committed
update README
[skip ci]
1 parent 4ec817d commit cb13093

File tree

1 file changed

+240
-57
lines changed

1 file changed

+240
-57
lines changed

README.md

Lines changed: 240 additions & 57 deletions
Original file line numberDiff line numberDiff line change
@@ -5,106 +5,289 @@ An elegant socket.io client for .NET, Supports `.NET Standard 2.0`, support sock
55
[![Build Status](https://herowong.visualstudio.com/socket.io-client/_apis/build/status/doghappy.socket.io-client-csharp?branchName=master)](https://herowong.visualstudio.com/socket.io-client/_build/latest?definitionId=15&branchName=master)
66
[![NuGet](https://img.shields.io/badge/NuGet-SocketIOClient-%23004880)](https://www.nuget.org/packages/SocketIOClient)
77

8-
# How to use
8+
# Table of Contents
9+
10+
- [Quick start](#quick-start)
11+
- Options
12+
- Ack
13+
- Binary messages
14+
- JsonSerializer
15+
- ClientWebSocket Options
16+
- Windows 7 Support
17+
- Breaking changes
18+
- Breaking changes in 3.x
19+
- Breaking changes in 2.2.4
20+
- Breaking changes in 2.2.0
21+
- Change log
22+
- Sponsors
23+
24+
# Quick start
25+
26+
Connect to the socket.io server, listen events and emit some data.
927

10-
[Wiki](https://github.com/doghappy/socket.io-client-csharp/wiki)
28+
```cs
29+
var client = new SocketIO("http://localhost:11000/");
1130

12-
# Breaking changes in 3.x (Not yet released)
31+
client.On("hi", response =>
32+
{
33+
// You can print the returned data first to decide what to do next.
34+
// output: ["hi client"]
35+
Console.WriteLine(response);
1336

14-
> While WebSocket is clearly the best way to establish a bidirectional communication, experience has shown that it is not always possible to establish a WebSocket connection, due to corporate proxies, personal firewall, antivirus software…
37+
string text = response.GetValue<string>();
1538

16-
https://socket.io/docs/v4/how-it-works/#Transports
39+
// The socket.io server code looks like this:
40+
// socket.emit('hi', 'hi client');
41+
});
1742

18-
- SocketIOClient v3.x supports http polling, but if websocket is available, the library will choose to use websocket. If you want to use http polling and do not want the library to upgrade the transport, please set `Options.AutoUpgrade = false`.
19-
- Socket.io server v2.x is no longer supported. If a large number of users use this version, please feedback.
43+
client.On("test", response =>
44+
{
45+
// You can print the returned data first to decide what to do next.
46+
// output: ["ok",{"id":1,"name":"tom"}]
47+
Console.WriteLine(response);
48+
49+
// Get the first data in the response
50+
string text = response.GetValue<string>();
51+
// Get the second data in the response
52+
var dto = response.GetValue<TestDTO>(1);
53+
54+
// The socket.io server code looks like this:
55+
// socket.emit('hi', 'ok', { id: 1, name: 'tom'});
56+
});
57+
58+
client.OnConnected += async (sender, e) =>
59+
{
60+
// Emit a string
61+
await client.EmitAsync("hi", "socket.io");
62+
63+
// Emit a string and an object
64+
var dto = new TestDTO { Id = 123, Name = "bob" };
65+
await client.EmitAsync("register", "source", dto);
66+
};
67+
await client.ConnectAsync();
68+
```
2069

21-
### Specific break changes
70+
## Options
2271

23-
#### 1. EIO option removed
72+
The way to override the default options is as follows:
2473

25-
Since socket.io server v2 is not supported, the EIO option is not required.
74+
```cs
75+
var client = new SocketIO("http://localhost:11000/", new SocketIOOptions
76+
{
77+
Query = new List<KeyValuePair<string, string>>
78+
{
79+
new KeyValuePair<string, string>("token", "abc123"),
80+
new KeyValuePair<string, string>("key", "value")
81+
}
82+
});
83+
```
2684

27-
#### 2. Removed the 'Socket' object
85+
| Option | Default value | Description |
86+
| :- | :- | :- |
87+
| `Path` | `/socket.io` | name of the path that is captured on the server side |
88+
| `Reconnection` | `true` | whether to reconnect automatically |
89+
| `ReconnectionAttempts` | `int.MaxValue` | number of reconnection attempts before giving up |
90+
| `ReconnectionDelay` | `1000` | how long to initially wait before attempting a new reconnection. Affected by +/- `RandomizationFactor`, for example the default initial delay will be between 500 to 1500ms. |
91+
| `RandomizationFactor` | `0.5` | 0 <= RandomizationFactor <= 1 |
92+
| `ConnectionTimeout` | `20000` | connection timeout |
93+
| `Query` | `IEnumerable<KeyValuePair<string, string>>` | additional query parameters that are sent when connecting a namespace (then found in `socket.handshake.query` object on the server-side) |
94+
| `AutoUpgrade` | `true` | If websocket is available, it will be automatically upgrade to use websocket |
2895

29-
Use ClientWebSocketProvider instead of Socket object.
96+
## Ack
3097

31-
# Breaking changes in 2.2.4
98+
### The server executes the client's ack function
3299

33-
Before SocketIOClient v2.2.4, the default EIO is 3, which works with socket.io v2.x, in SocketIOClient v2.2.4, the default EIO is 4, which works with socket.io v3.x and v4.x
100+
**Client**
101+
102+
```cs
103+
await client.EmitAsync("ack", response =>
104+
{
105+
// You can print the returned data first to decide what to do next.
106+
// output: [{"result":true,"message":"Prometheus - server"}]
107+
Console.WriteLine(response);
108+
var result = response.GetValue<BaseResult>();
109+
}, "Prometheus");
110+
```
34111

35-
# Breaking changes in 2.2.0
112+
**Server**
36113

37-
SocketIOClient v2.2.0 makes `System.Text.Json` the default JSON serializer. If you'd like to continue to use `Newtonsoft.Json`, add the **SocketIOClient.Newtonsoft.Json** NuGet package and set your **JsonSerializer** to **NewtonsoftJsonSerializer** on your SocketIO instance. System.Text.Json is faster and uses less memory.
114+
```js
115+
socket.on("ack", (name, fn) => {
116+
fn({
117+
result: true,
118+
message: `${name} - server`
119+
});
120+
});
121+
```
122+
123+
### The client executes the server's ack function
38124

39-
### Continue to use Newtonsoft.Json
125+
**Client**
40126

41127
```cs
42-
var client = new SocketIO("http://localhost:11000/");
43-
client.JsonSerializer = new NewtonsoftJsonSerializer(client.Options.EIO);
128+
client.On("ack2", async response =>
129+
{
130+
// You can print the returned data first to decide what to do next.
131+
// output: [1, 2]
132+
Console.WriteLine(response);
133+
int a = response.GetValue<int>();
134+
int b = response.GetValue<int>(1);
135+
136+
await response.CallbackAsync(b, a);
137+
});
138+
```
139+
140+
**Server**
141+
142+
```js
143+
socket.emit("ack2", 1, 2, (arg1, arg2) => {
144+
console.log(`arg1: ${arg1}, arg2: ${arg2}`);
145+
});
44146
```
45147

46-
### Custom JsonSerializerOptions/System.Text.Json
148+
The output of the server is:
149+
150+
```
151+
arg1: 2, arg2: 1
152+
```
153+
154+
## Binary messages
155+
156+
This example shows how to emit and receive binary messages, The library uses System.Text.Json to serialize and deserialize json by default.
47157

48158
```cs
49-
class MyJsonSerializer : SystemTextJsonSerializer
159+
class FileDTO
50160
{
51-
public MyJsonSerializer(int eio) : base(eio) {}
161+
[JsonPropertyName("name")]
162+
public string Name { get; set; }
52163

53-
public override JsonSerializerOptions CreateOptions()
54-
{
55-
var options = new JsonSerializerOption();
56-
options.PropertyNameCaseInsensitive = true;
57-
return options;
58-
}
164+
[JsonPropertyName("mimeType")]
165+
public string MimeType { get; set; }
166+
167+
[JsonPropertyName("bytes")]
168+
public byte[] Bytes { get; set; }
59169
}
170+
```
60171

61-
// ...
172+
```cs
173+
client.OnConnected += async (sender, e) =>
174+
{
175+
await client.EmitAsync("upload", new FileDTO
176+
{
177+
Name = "template.html"
178+
MimeType = "text/html",
179+
bytes = Encoding.UTF8.GetBytes("<div>test</div>")
180+
});
181+
};
62182

183+
client.On("new files", response =>
184+
{
185+
// You can print the returned data first to decide what to do next.
186+
// output: [{"name":"template.html","mimeType":"text/html","bytes":{"_placeholder":true,"num":0}}]
187+
Console.WriteLine(response);
188+
var result = response.GetValue<FileDTO>();
189+
Console.WriteLine(Encoding.UTF8.GetString(result.Bytes))
190+
});
191+
```
192+
193+
## JsonSerializer
194+
195+
The library uses System.Text.Json to serialize and deserialize json by default, If you want to change JsonSerializerOptions, you can do this:
196+
197+
```cs
63198
var client = new SocketIO("http://localhost:11000/");
64-
client.JsonSerializer = new MyJsonSerializer(client.Options.EIO);
199+
var jsonSerializer = socket.JsonSerializer as SystemTextJsonSerializer;
200+
jsonSerializer.OptionsProvider = () => new JsonSerializerOptions
201+
{
202+
PropertyNameCaseInsensitive = true
203+
};
65204
```
66205

67-
### Custom JsonSerializerSettings/Newtonsoft.Json
206+
Of course you can also use Newtonsoft.Json library, for this, you need to install `SocketIOClient.Newtonsoft.Json` dependency.
68207

69208
```cs
70-
class MyJsonSerializer : NewtonsoftJsonSerializer
209+
var jsonSerializer = new NewtonsoftJsonSerializer();
210+
jsonSerializer.OptionsProvider = () => new JsonSerializerSettings
71211
{
72-
public MyJsonSerializer(int eio) : base(eio) {}
212+
ContractResolver = new DefaultContractResolver
213+
{
214+
NamingStrategy = new CamelCaseNamingStrategy()
215+
}
216+
};
217+
socket.JsonSerializer = jsonSerializer;
218+
```
73219

74-
public override JsonSerializerSettings CreateOptions()
220+
## ClientWebSocket Options
221+
222+
You can set proxy and add headers for WebSocket client, etc.
223+
224+
```cs
225+
var client = new SocketIO("http://localhost:11000/");
226+
client.ClientWebSocketProvider = () =>
227+
{
228+
var clientWebSocket = new DefaultClientWebSocket
75229
{
76-
return new JsonSerializerSettings
230+
ConfigOptions = o =>
77231
{
78-
ContractResolver = new global::Newtonsoft.Json.Serialization.DefaultContractResolver
232+
var options = o as ClientWebSocketOptions;
233+
234+
var proxy = new WebProxy("http://example.com");
235+
proxy.Credentials = new NetworkCredential("username", "password");
236+
options.Proxy = proxy;
237+
238+
options.SetRequestHeader("key", "value");
239+
240+
options.RemoteCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) =>
79241
{
80-
NamingStrategy = new global::Newtonsoft.Json.Serialization.CamelCaseNamingStrategy()
81-
},
82-
Formatting = Formatting.Indented
83-
};
84-
}
85-
}
242+
Console.WriteLine("SslPolicyErrors: " + sslPolicyErrors);
243+
if (sslPolicyErrors == System.Net.Security.SslPolicyErrors.None)
244+
{
245+
return true;
246+
}
247+
return true;
248+
};
249+
}
250+
};
251+
return clientWebSocket;
252+
};
253+
```
86254

87-
// ...
255+
## Windows 7 Support
88256

89-
var client = new SocketIO("http://localhost:11000/");
90-
client.JsonSerializer = new MyJsonSerializer(client.Options.EIO);
257+
The library uses System.Net.WebSockets.ClientWebSocket by default. Unfortunately, it does not support Windows 7 or Windows Server 2008 R2. You will get a PlatformNotSupportedException. To solve this problem, you need to install the `SocketIOClient.Windows7` dependency and then change the implementation of ClientWebSocket.
258+
259+
```cs
260+
client.ClientWebSocketProvider = () => new ClientWebSocketManaged();
91261
```
92262

93-
# Development
263+
# Breaking changes
94264

95-
Before development or testing, you need to install the nodejs.
265+
## Breaking changes in 3.x
96266

97-
```bash
98-
# start socket.io v2 server
99-
cd src/socket.io-server-v2
100-
npm i # If the dependencies are already installed, you can ignore this step.
101-
npm start
267+
> While WebSocket is clearly the best way to establish a bidirectional communication, experience has shown that it is not always possible to establish a WebSocket connection, due to corporate proxies, personal firewall, antivirus software…
102268
103-
# start socket.io v3 server
104-
cd src/socket.io-server-v3
105-
npm i # If the dependencies are already installed, you can ignore this step.
106-
npm start
107-
```
269+
https://socket.io/docs/v4/how-it-works/#Transports
270+
271+
- SocketIOClient v3.x supports http polling, but if websocket is available, the library will choose to use websocket. If you want to use http polling and do not want the library to upgrade the transport, please set `Options.AutoUpgrade = false`.
272+
- Socket.io server v2.x is no longer supported. If a large number of users use this version, please feedback.
273+
274+
### Specific break changes
275+
276+
#### 1. EIO option removed
277+
278+
Since socket.io server v2 is not supported, the EIO option is not required.
279+
280+
#### 2. Removed the 'Socket' object
281+
282+
Use ClientWebSocketProvider instead of Socket object.
283+
284+
## Breaking changes in 2.2.4
285+
286+
Before SocketIOClient v2.2.4, the default EIO is 3, which works with socket.io v2.x, in SocketIOClient v2.2.4, the default EIO is 4, which works with socket.io v3.x and v4.x
287+
288+
## Breaking changes in 2.2.0
289+
290+
SocketIOClient v2.2.0 makes `System.Text.Json` the default JSON serializer. If you'd like to continue to use `Newtonsoft.Json`, add the **SocketIOClient.Newtonsoft.Json** NuGet package and set your **JsonSerializer** to **NewtonsoftJsonSerializer** on your SocketIO instance. System.Text.Json is faster and uses less memory.
108291

109292
# Change log
110293

0 commit comments

Comments
 (0)