Overview
The Chat WebSocket API provides a real-time bidirectional communication channel that enables multi-user chat applications. This API handles message broadcasting, tracks user presence (who joins and leaves), and simulates other users responding to messages.
Key Features
- Real-time message broadcasting to all connected clients
- User presence notifications (join/leave events)
- Automated mock chat responses for testing user interactions
- JSON-formatted messages with timestamps and unique IDs
- System messages for connection status and events
Connection
To connect to the Chat WebSocket API, use the following endpoint:
wss://mockly.me/ws/chat/{client_id}
Replace {client_id}
with a unique identifier for the user connecting to the chat. This ID will be visible to other users in the chat room.
Connection Code Examples
// Connect to the chat WebSocket
const clientId = 'user_' + Math.floor(Math.random() * 10000);
const chatSocket = new WebSocket(`wss://mockly.me/ws/chat/${clientId}`);
// Handle connection open
chatSocket.onopen = (event) => {
console.log('Connected to chat server');
// Update UI to show connected state
document.getElementById('connection-status').textContent = 'Connected';
document.getElementById('connection-status').classList.add('text-green-600');
};
// Handle messages
chatSocket.onmessage = (event) => {
const data = JSON.parse(event.data);
console.log('Message received:', data);
// Handle different message types
switch(data.type) {
case 'system':
displaySystemMessage(data);
break;
case 'message':
displayChatMessage(data);
break;
case 'error':
displayErrorMessage(data);
break;
}
};
// Handle connection close
chatSocket.onclose = (event) => {
console.log('Disconnected from chat server');
// Update UI to show disconnected state
document.getElementById('connection-status').textContent = 'Disconnected';
document.getElementById('connection-status').classList.remove('text-green-600');
document.getElementById('connection-status').classList.add('text-red-600');
};
import asyncio
import json
import random
import websockets
async def connect_to_chat():
client_id = f"user_{random.randint(1000, 9999)}"
uri = f"wss://mockly.me/ws/chat/{client_id}"
async with websockets.connect(uri) as websocket:
print(f"Connected to chat as {client_id}")
# Handle incoming messages in background task
async def receive_messages():
while True:
try:
message = await websocket.recv()
data = json.loads(message)
# Handle different message types
if data["type"] == "system":
print(f"SYSTEM: {data['message']}")
elif data["type"] == "message":
print(f"{data['sender']}: {data['message']}")
elif data["type"] == "error":
print(f"ERROR: {data['message']}")
except websockets.exceptions.ConnectionClosed:
print("Connection closed")
break
# Start receiving messages in background
receive_task = asyncio.create_task(receive_messages())
# Send messages from command line
try:
while True:
message = input("Enter message: ")
if message.lower() == "exit":
break
await websocket.send(json.dumps({
"message": message
}))
finally:
receive_task.cancel()
# Run the chat client
asyncio.run(connect_to_chat())
import java.net.URI;
import java.util.Random;
import java.util.concurrent.CountDownLatch;
import javax.websocket.*;
import org.glassfish.tyrus.client.ClientManager;
import org.json.JSONObject;
@ClientEndpoint
public class ChatClient {
private Session session;
@OnOpen
public void onOpen(Session session) {
this.session = session;
System.out.println("Connected to chat server");
}
@OnMessage
public void onMessage(String message) {
JSONObject data = new JSONObject(message);
// Handle different message types
String type = data.getString("type");
switch (type) {
case "system":
System.out.println("SYSTEM: " + data.getString("message"));
break;
case "message":
System.out.println(data.getString("sender") + ": " + data.getString("message"));
break;
case "error":
System.out.println("ERROR: " + data.getString("message"));
break;
}
}
@OnClose
public void onClose(Session session, CloseReason reason) {
System.out.println("Disconnected from chat server: " + reason);
this.session = null;
}
public void sendMessage(String text) {
if (session != null) {
JSONObject message = new JSONObject();
message.put("message", text);
session.getAsyncRemote().sendText(message.toString());
}
}
public static void main(String[] args) {
try {
final ChatClient client = new ChatClient();
final CountDownLatch latch = new CountDownLatch(1);
// Generate a random client ID
Random random = new Random();
String clientId = "user_" + (1000 + random.nextInt(9000));
// Connect to the chat server
ClientManager clientManager = ClientManager.createClient();
clientManager.connectToServer(client,
URI.create("wss://mockly.me/ws/chat/" + clientId));
// Allow the user to send messages
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter messages (type 'exit' to quit):");
String line;
while ((line = reader.readLine()) != null) {
if ("exit".equalsIgnoreCase(line.trim())) {
break;
}
client.sendMessage(line);
}
latch.await();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Message Format
Sending Messages
To send a message to the chat room, send a JSON object with the following format:
{
"message": "Hello, everyone!"
}
Receiving Messages
You will receive messages in the following JSON formats:
Chat Message
{
"type": "message",
"sender": "user_1234",
"sender_name": "John Doe", // Optional, for bot messages
"sender_avatar": "https://...", // Optional, for bot messages
"message": "Hello, everyone!",
"timestamp": "2023-07-25T14:32:15.123456",
"id": "msg_5678"
}
System Message
{
"type": "system",
"message": "user_5678 has joined the chat",
"timestamp": "2023-07-25T14:30:05.123456",
"online_users": 3
}
Error Message
{
"type": "error",
"message": "Invalid JSON format",
"timestamp": "2023-07-25T14:33:25.123456"
}
Events
The Chat WebSocket API generates the following events:
Event | Description |
---|---|
Connection | When a user connects, they receive a welcome message and other users are notified about the new user joining. |
Message | When a user sends a message, it's broadcast to all connected users including the sender. |
Bot Response | With a 30% chance after each user message, a simulated bot user will respond with a random message. |
Disconnection | When a user disconnects, other users are notified about the user leaving. |
Live Chat Demo
Try the WebSocket Chat API directly in your browser with this live demo:
Chat Demo
DisconnectedAbout this demo:
- You're connected with a random user ID
- Chat messages are broadcast to everyone using this demo
- Bot users may occasionally respond to messages
- System messages show who's joining and leaving
- The connection will automatically try to reconnect if disconnected
- This is a shared chat room - be respectful to others testing the API
Meet Mockly Assistant
Your AI assistant for API testing, debugging and code generation. Access the power of mockly.me directly in ChatGPT.
- Generate code examples in your preferred language
- Get guidance for request/response handling and formatting
- Supercharged by ChatGPT Plus from OpenAI
"How do I send data to a POST endpoint"
"I can show you how to structure your request with headers and JSON — here's a code example..."