Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions src/main/java/io/socket/client/Socket.java
Original file line number Diff line number Diff line change
Expand Up @@ -201,6 +201,21 @@ public Emitter emit(final String event, final Object[] args, final Ack ack) {
EventThread.exec(new Runnable() {
@Override
public void run() {
// warn if any argument is a JSON-looking string (common pitfall)
if (args != null) {
for (Object arg : args) {
if (arg instanceof CharSequence) {
String s = arg.toString().trim();
boolean looksLikeJsonObject = s.startsWith("{") && s.endsWith("}");
boolean looksLikeJsonArray = s.startsWith("[") && s.endsWith("]");
if (looksLikeJsonObject || looksLikeJsonArray) {
logger.warning("Emitting a JSON-looking string. If you intend to send structured data, pass a JSONObject/JSONArray instead of a string.");
break;
}
}
}
}

JSONArray jsonArgs = new JSONArray();
jsonArgs.put(event);

Expand Down
17 changes: 17 additions & 0 deletions src/site/markdown/emitting_events.md
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,23 @@ object.put("test", "42");
socket.emit("hello", 1, "2", bytes, object);
```

### Common pitfall: stringified JSON

If you intend to send structured data, do not pass a JSON-looking string like `"{me: 1449240991}"`. Send a `JSONObject` (or `JSONArray`) instead. Strings will be delivered as plain strings on the server.

Client (wrong):

```java
socket.emit("authentication", "{me: 1449240991}"); // sent as a String, not an object
```

Client (correct):

```java
JSONObject payload = new JSONObject().put("me", 1449240991);
socket.emit("authentication", payload);
```

## Acknowledgements

Events are great, but in some cases you may want a more classic request-response API. In Socket.IO, this feature is named acknowledgements.
Expand Down