Skip to content

Commit d97f457

Browse files
docs: add example with server to client ack
Related: #693
1 parent d8d975e commit d97f457

File tree

1 file changed

+47
-4
lines changed

1 file changed

+47
-4
lines changed

src/site/markdown/emitting_events.md

Lines changed: 47 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,27 @@ Events are great, but in some cases you may want a more classic request-response
7777

7878
You can add a callback as the last argument of the `emit()`, and this callback will be called once the other side acknowledges the event:
7979

80+
### From client to server
81+
82+
*Client*
83+
84+
```java
85+
// Java 7
86+
socket.emit("update item", 1, new JSONObject(singletonMap("name", "updated")), new Ack() {
87+
@Override
88+
public void call(Object... args) {
89+
JSONObject response = (JSONObject) args[0];
90+
System.out.println(response.getString("status")); // "ok"
91+
}
92+
});
93+
94+
// Java 8 and above
95+
socket.emit("update item", 1, new JSONObject(singletonMap("name", "updated")), (Ack) args -> {
96+
JSONObject response = (JSONObject) args[0];
97+
System.out.println(response.getString("status")); // "ok"
98+
});
99+
```
100+
80101
*Server*
81102

82103
```js
@@ -91,15 +112,37 @@ io.on("connection", (socket) => {
91112
});
92113
```
93114

115+
### From server to client
116+
117+
*Server*
118+
119+
```js
120+
io.on("connection", (socket) => {
121+
socket.emit("hello", "please acknowledge", (response) => {
122+
console.log(response); // prints "hi!"
123+
});
124+
});
125+
```
126+
94127
*Client*
95128

96129
```java
97-
socket.emit("update item", 1, new JSONObject(singletonMap("name", "updated")), new Ack() {
130+
// Java 7
131+
socket.on("hello", new Emitter.Listener() {
98132
@Override
99133
public void call(Object... args) {
100-
JSONObject response = (JSONObject) args[0];
101-
System.out.println(response.getString("status")); // "ok"
134+
System.out.println(args[0]); // "please acknowledge"
135+
if (args.length > 1 && args[1] instanceof Ack) {
136+
((Ack) args[1]).call("hi!");
137+
}
102138
}
103139
});
104-
```
105140

141+
// Java 8 and above
142+
socket.on("hello", args -> {
143+
System.out.println(args[0]); // "please acknowledge"
144+
if (args.length > 1 && args[1] instanceof Ack) {
145+
((Ack) args[1]).call("hi!");
146+
}
147+
});
148+
```

0 commit comments

Comments
 (0)