Introduction to nssocket
nssocket
is a robust and simple framework for building TCP clients and servers in Node.js. With nssocket
, developers can easily handle event-driven networking to build scalable and reliable messaging systems, chat applications, and more.
Basic API Reference and Examples
Creating a Server
const nssocket = require('nssocket');
const server = nssocket.createServer(function (socket) {
socket.send(['hi'], 'Hello World!');
});
server.listen(6785);
console.log('Server is listening on port 6785');
Creating a Client
const nssocket = require('nssocket');
const socket = new nssocket.NsSocket({
reconnect: true
});
socket.connect(6785);
socket.on('data', function (data) {
console.log('Received: ' + data);
});
socket.send(['message'], 'Hello Server!');
Event Handling
const nssocket = require('nssocket');
const server = nssocket.createServer(function (socket) {
socket.on('greeting', function (data) {
console.log('Greeting received:', data);
socket.send(['response'], 'Hello Client!');
});
});
server.listen(6785, function() {
console.log('Server is running on port 6785');
});
Broadcasting Messages
const nssocket = require('nssocket');
const server = nssocket.createServer(function (socket) {
setInterval(function() {
socket.send(['news'], 'Breaking News!');
}, 5000);
});
server.listen(6785);
Advanced Example
Below is an example of a simple chat application using the APIs discussed above.
Server for Chat Application
const nssocket = require('nssocket');
const clients = [];
const server = nssocket.createServer(function (socket) {
clients.push(socket);
socket.on('message', function (data) {
console.log('Message received: ' + data);
clients.forEach(client => {
if (client !== socket) {
client.send(['chat'], data);
}
});
});
socket.on('close', function () {
const index = clients.indexOf(socket);
if (index !== -1) {
clients.splice(index, 1);
}
});
});
server.listen(6785, function () {
console.log('Chat server running on port 6785');
});
Client for Chat Application
const nssocket = require('nssocket');
const socket = new nssocket.NsSocket();
socket.connect(6785);
socket.on('chat', function (data) {
console.log('Chat message: ' + data);
});
process.stdin.on('data', function (data) {
socket.send(['message'], data.toString().trim());
});
Hash: a4cc29ba8ef5d1265196dde00d057a6ff8e66a3acf206e6004b7e863f21d4277