Created
June 7, 2020 09:49
-
-
Save erkanzileli/ae670c64491d51d03e25fd3b7ce4096a to your computer and use it in GitHub Desktop.
Sample WebSocket Server with Node.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const http = require('http') | |
const WebSocketServer = require('websocket').server | |
const PORT = process.env.PORT || 8080 | |
const MessageType = { | |
Join: 'Join', | |
Left: 'Left', | |
Message: 'Message' | |
} | |
var CLIENTS = [] | |
var MESSAGES = [] | |
/** | |
* Create a message from single function. I think that provides more readability. | |
* @param {string} type Message type | |
* @param {string} client Request key | |
* @param {string} text Message body | |
*/ | |
function createMessage (type, client, text) { | |
if (type === MessageType.Message) { | |
return { | |
type, client, text | |
} | |
} else if ([MessageType.Join, MessageType.Left].includes(type)) { | |
return { | |
type, client | |
} | |
} | |
throw new Error('Unknown message type!') | |
} | |
function saveClient (connection) { | |
CLIENTS = [...CLIENTS, { connection }] | |
const message = createMessage(MessageType.Join, connection.key) | |
broadCast(message) | |
} | |
function deleteClient (connection) { | |
CLIENTS = CLIENTS.filter(client => client.key !== connection.key) | |
} | |
function saveMessage (message) { | |
MESSAGES = [...MESSAGES, message] | |
} | |
function publishMessage (msg, clientKey) { | |
const message = JSON.stringify(msg) | |
CLIENTS.forEach(client => { | |
if (client.key !== clientKey) { | |
client.connection.sendUTF(message) | |
} | |
}) | |
} | |
function broadCast (msg) { | |
const message = JSON.stringify(msg) | |
CLIENTS.forEach(client => { | |
client.connection.sendUTF(message) | |
}) | |
} | |
const server = http.createServer(function (request, response) { | |
console.log(new Date() + ' Received request for ' + request.url) | |
response.writeHead(404) | |
response.end() | |
}) | |
server.listen(8080, function () { | |
console.log(`${new Date()} Server is listening on port ${PORT}`) | |
}) | |
const ws = new WebSocketServer({ httpServer: server }) | |
function originIsAllowed (origin) { | |
return true | |
} | |
ws.on('request', request => { | |
if (!originIsAllowed(request.origin)) { | |
request.reject() | |
console.log( | |
`${new Date()} Connection from origin ${request.origin} rejected` | |
) | |
return | |
} | |
const connection = request.accept() | |
connection.key = request.key | |
saveClient(connection) | |
connection.on('message', message => { | |
if (message.type === 'utf8') { | |
message = JSON.parse(message.utf8Data) | |
if (message.type === MessageType.Message) { | |
const msg = createMessage(message.type, connection.key, message.text) | |
saveMessage(msg) | |
publishMessage(msg, connection.key) | |
} | |
} else if (message.type === 'binary') { | |
console.log( | |
`Received Binary Message of ${message.binaryData.length} bytes` | |
) | |
connection.sendBytes(message.binaryData) | |
} | |
}) | |
connection.on('close', (reasonCode, description) => { | |
deleteClient(connection.key) | |
const message = createMessage(MessageType.Left, connection.key) | |
broadCast(message) | |
console.log(`${new Date()} Peer ${connection.remoteAddress} disconnected.`) | |
}) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment