I am very new to this, and am attempting to create a cross-client chat server. My only problem is that I am unsure on how to connect to my local ip from another computer via a SockJS socket. Currently, the relevant code is as follows:
Client:
$(() => {
var url = window.location.protocol + '//' + window.location.host;
sock = new SockJS(url)
sock.onmessage = function(e) {
var content = JSON.parse(e.data)
$('#chat-content').val(function(i, text){
textarea.scrollTop = textarea.scrollHeight
return text + content.username + ': ' + content.message + '\n'
})
}
})
Server:
var http = require('http')
var sockjs = require('sockjs')
var clients = {}
function broadcast(message){
for (var client in clients){
clients[client].write(JSON.stringify(message))
}
}
var echo = sockjs.createServer()
echo.on('connection', function(conn) {
clients[conn.id] = conn
conn.on('data', function(message) {
broadcast(JSON.parse(message))
})
conn.on('close', function() {
delete clients[conn.id]
})
})
var server = http.createServer((req, res) => {
res.writeHead(200, { 'content-type': 'text/html' })
fs.createReadStream('index.html').pipe(res)
})
echo.installHandlers(server, {prefix:'/echo'})
server.listen(8080, '0.0.0.0')
When I attempt to connect to this via my ip, the html console shows
WebSocket connection to 'ws://redacted:8080/redacted/redacted/websocket' failed:
WebSocket is closed before the connection is established.
"redacted" is a placeholder for something I'm not sure if I should share.