Introduction to agora-ws
Welcome to the world of agora-ws, a powerful WebSocket library designed
to enhance real-time communication in your applications. Whether you are building a chat
application, a collaborative platform, or any other real-time communication tool,
agora-ws
has you covered with its robust and easy-to-use APIs.
API Examples
1. Initializing a WebSocket Connection
To start with agora-ws
, you need to initialize a WebSocket connection.
const agoraWs = new AgoraWS('wss://example.com/socket');
agoraWs.on('open', () => {
console.log('WebSocket connection opened');
});
agoraWs.on('close', () => {
console.log('WebSocket connection closed');
});
agoraWs.on('error', (error) => {
console.error('WebSocket error:', error);
});
2. Sending Messages
Sending messages with agora-ws
is straightforward.
agoraWs.send('Hello, World!');
agoraWs.on('message', (message) => {
console.log('Received message:', message);
});
3. Subscribing to Events
You can subscribe to various events like message receipt, connection opening, and errors.
agoraWs.on('customEvent', (data) => {
console.log('Custom event received:', data);
});
// Triggering a custom event
agoraWs.emit('customEvent', { key: 'value' });
4. Closing the Connection
Gracefully close the WebSocket connection when it is no longer needed.
agoraWs.close();
5. Reconnecting
Handle connection disruptions and automatically attempt to reconnect.
agoraWs.on('disconnect', () => {
console.log('Disconnected. Attempting to reconnect...');
agoraWs.reconnect();
});
App Example with agora-ws
Here is a simple chat application example using the agora-ws
library:
// Initialize WebSocket
const agoraWs = new AgoraWS('wss://chat.example.com/socket');
// Open connection
agoraWs.on('open', () => {
console.log('Connected to chat server');
});
// Receive messages
agoraWs.on('message', (message) => {
displayMessage(message);
});
// Send message
document.getElementById('sendBtn').addEventListener('click', () => {
const message = document.getElementById('messageInput').value;
agoraWs.send(message);
});
// Display message in chat window
function displayMessage(message) {
const chatWindow = document.getElementById('chatWindow');
const messageElement = document.createElement('div');
messageElement.textContent = message;
chatWindow.appendChild(messageElement);
}
With this setup, you can create an interactive chat application using agora-ws
to handle real-time messaging efficiently.
Hash: 175a2aa57f2af4a647da36574ef220004e24052c828f9ac43509b92ae954fa00