I have two files named test.html and server.py and I am trying to make a WebSocket server.
Hence test.html is a client-side and server.py is server-side.
But Websocket server is not loading, please find below code :
test.html
<p id="status">Connecting...</p>
<input id="message" />
<button id="submit">Send</button>
<script>
var socket = new WebSocket('wss://starlite3.tk/IncreedibleTanksServer');
socket.onopen = function() {
document.getElementById("status").innerHTML="Connected";
}
document.getElementById("submit").addEventListener("click", function() {
socket.send(document.getElementById("message").value);
});
socket.onmessage = function(e) {
alert(e.data);
}
socket.onerrror = function(e) {
document.getElementById("status").innerHTML = "ERROR: "+e.target.CONNECTING
}
</script>
server.py
import websockets
def start(websocket, uri):
websocket.send('HI')
websockets.server.serve(start, "starlite3.tk", 0);
Related
File in Desktop Image : index.html
Error Message Image : WebSocket connection to 'wss://graphigostream.prd.dlive.tv/' failed:
connect # index.html:9
File Path : file:///C:/Users/.../Desktop/index.html
Code:
<!doctype html>
<html>
<head>
</head>
<script>
function connect() {
var ws = new WebSocket('wss://graphigostream.prd.dlive.tv/', "graphql-ws");
ws.onopen = function() {
// ...
};
ws.onmessage = function(e) {
// ...
}
ws.onclose = function(e) {
// ...
};
ws.onerror = function(err) {
// ...
};
}
connect()
</script>
<body>
</body>
</html>
I want run this WebSocket through an HTML file, this url works in Nodejs, another website has the same and it works, I checked "window.WebSocket"
I am using sockets to send a file. On the server side I am listening to stream from the client side, but from the client side, I am not able to send data in chunks which can be sent to the server side.
I used FileReader to read the file in slices can you please tell what is that I am doing wrong?
Client Code
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Echo server</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
<h1>File Upload</h1>
<form id="form" id="chat_form">
<input type="file" id="file_input" />
<input type="button" onclick="submit1()" value="submit">
</form>
<script src="socket.io/socket.io.js"></script>
<script type="text/javascript">
var socket = io('localhost:8080');
var fReader;
socket.on('echo', function (data) {
console.log(data);
});
socket.emit('echo', 'this is a message');
function submit1() {
var file = $("#file_input")[0].files[0];
var reader = new FileReader();
reader.onload = function (evnt) {
socket.emit('join', { 'Name': Name, Data: evnt.target.result });
}
reader.readAsArrayBuffer(file);
}
</script>
</body>
</head>
SERVER code
var http = require('http')
var fs = require('fs');
var express = require('express')
var socketio = require('socket.io')
var app = express(server)
var server = http.Server(app)
var io = socketio(server)
app.get('/', function(req, res){
res.sendFile(__dirname + '/client.html')
});
io.on('connection', function(socket){
var writeStream = fs.createWriteStream(__dirname +'/m.png');
socket.on('echo', function(data){
socket.emit('echo', data);
});
socket.on('join', function(chunk){
console.log(chunk, "==============chunk=====================");
writeStream.write(chunk);
})
});
You never give the file object to your FileReader object. In fact, you never do anything with it so the FileReader object never has anything to do. For example, you may want to do:
reader.readAsArrayBuffer(file);
It also doesn't look like you're getting the data from the reader object correctly. There's a code examples here: File upload with socket.io and Send Images through Websockets.
I need to connect HTML website to node server chat application. HTML client side has some HTML files and javascript file.I need to connect socket.io chat server using javascript. So it needs to initialize socket.io port inside javascript.
I have created socket.io chat server in node.js using javascript it is working fine. And I need to call that node server using javascript client site.
It should initialize and socket server connect. It should able to emit and receive messages from the server site.
I have a socket.io backend service which is working fine. Because I test it with nodeJS client application. But I need it to use existing HTML web site which is not nodeJS
I have searched on google and can't find any website which is about connecting sockt.io using a javascript file. All tutorials are using nodeJS.
When I used
var io = require('socket.io').listen(server);
inside the javascript file and open HTML page in the browser, it throws an error.
This is my code, I got this from the internet I was trying to connect this implement my real code.
<!DOCTYPE html>
<html>
<head>
<link href="style.css" rel="stylesheet">
<script src="http://code.jquery.com/jquery-1.6.1.min.js"></script>
<script src="/socket.io/socket.io.js"></script>
<script>
// socket.io specific code
var socket = io.connect('http://localhost:8000');
socket.on('connect', function () {
$('#chat').addClass('connected');
});
socket.on('announcement', function (msg) {
$('#lines').append($('<p>').append($('<em>').text(msg)));
});
socket.on('nicknames', function (nicknames) {
$('#nicknames').empty().append($('<span>Online: </span>'));
for (var i in nicknames) {
$('#nicknames').append($('<b>').text(nicknames[i]));
}
});
socket.on('user message', message);
socket.on('reconnect', function () {
$('#lines').remove();
message('System', 'Reconnected to the server');
});
socket.on('reconnecting', function () {
message('System', 'Attempting to re-connect to the server');
});
socket.on('error', function (e) {
message('System', e ? e : 'A unknown error occurred');
});
function message(from, msg) {
$('#lines').append($('<p>').append($('<b>').text(from), msg));
}
// dom manipulation
$(function () {
$('#set-nickname').submit(function (ev) {
socket.emit('nickname', $('#nick').val(), function (set) {
if (!set) {
clear();
return $('#chat').addClass('nickname-set');
}
$('#nickname-err').css('visibility', 'visible');
});
return false;
});
$('#send-message').submit(function () {
message('me', $('#message').val());
socket.emit('user message', $('#message').val());
clear();
$('#lines').get(0).scrollTop = 10000000;
return false;
});
function clear() {
$('#message').val('').focus();
};
});
</script>
</head>
<body>
<div id="chat">
<div id="nickname">
<form id="set-nickname" class="wrap">
<p>Please type in your nickname and press enter.</p>
<input id="nick">
<p id="nickname-err">Nickname already in use</p>
</form>
</div>
<div id="connecting">
<div class="wrap">Connecting to socket.io server</div>
</div>
<div id="messages">
<div id="nicknames"></div>
<div id="lines"></div>
</div>
<form id="send-message">
<input id="message">
<button>Send</button>
</form>
</div>
</body>
</html>
Error in the front end:
Uncaught ReferenceError: io is not defined
at chat-footer.html:10
This is my folder structure:
var io = require('socket.io').listen(server); should be on the server side. var socket=io(); should be in the client side javascript. If you are putting var io in the client side then you would get an error. Plus you need to link the socket io library in the <head> tag of the HTML: <script src='/socket.io/socket.io.js'></script>. If you do not have the library linked the io() function will not work. I hope that this solves your problem.
UPDATED
According to your code. You never defined the io(); function. You went ahead in the front end and said var socket = io.connect(). You never said what io is. What it should be is name a different variable var socket = io(); and then use var connector = io.connect().
SECOND UPDATE
If the html page is not being served from the nodejs backend, you will not be able to use socketio as it is not connected to a server. You need to serve the html page from the backend and use socketio on the same backend server.
I have resolved the error. The reason was I cannot add a socket.io reference directly because it's nodeJS script. So I added socket.io.js from nodeJS service library. By adding that my HTML page will directly refer running nodeJS server socket.io.js file.
This is my working and complete code to connect socket.io nodeJS server.
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.6.1.min.js"></script>
<script src="http://localhost:8000/socket.io/socket.io.js"></script> // add this line
<script>
var socket = io.connect('http://localhost:8000');
socket.on('connect', function () {
$('#chat').addClass('connected');
});
socket.on('announcement', function (msg) {
$('#lines').append($('<p>').append($('<em>').text(msg)));
});
socket.on('nicknames', function (nicknames) {
$('#nicknames').empty().append($('<span>Online: </span>'));
for (var i in nicknames) {
$('#nicknames').append($('<b>').text(nicknames[i]));
}
});
socket.on('user message', message);
socket.on('reconnect', function () {
$('#lines').remove();
message('System', 'Reconnected to the server');
});
socket.on('reconnecting', function () {
message('System', 'Attempting to re-connect to the server');
});
socket.on('error', function (e) {
message('System', e ? e : 'A unknown error occurred');
});
function message(from, msg) {
$('#lines').append($('<p>').append($('<b>').text(from), msg));
}
// dom manipulation
$(function () {
$('#set-nickname').submit(function (ev) {
socket.emit('nickname', $('#nick').val(), function (set) {
if (!set) {
clear();
return $('#chat').addClass('nickname-set');
}
$('#nickname-err').css('visibility', 'visible');
});
return false;
});
$('#send-message').submit(function () {
message('me', $('#message').val());
socket.emit('user message', $('#message').val());
clear();
$('#lines').get(0).scrollTop = 10000000;
return false;
});
function clear() {
$('#message').val('').focus();
};
});
</script>
</head>
<body>
<div id="chat">
<div id="nickname">
<form id="set-nickname" class="wrap">
<p>Please type in your nickname and press enter.</p>
<input id="nick">
<p id="nickname-err">Nickname already in use</p>
</form>
</div>
<div id="connecting">
<div class="wrap">Connecting to socket.io server</div>
</div>
<div id="messages">
<div id="nicknames"></div>
<div id="lines"></div>
</div>
<form id="send-message">
<input id="message">
<button>Send</button>
</form>
</div>
</body>
</html>
I've set up a very basic websocket server using flask.
websocket.py
from flask import Flask
from flask_uwsgi_websocket import GeventWebSocket
app = Flask(__name__)
ws = GeventWebSocket(app)
#app.route('/')
def index():
return render_template('index.html')
#ws.route('/foobar')
def echo(wscon):
msg = wscon.receive()
if msg is not None:
wscon.send(msg)
if __name__ == '__main__':
app.run(gevent=1000, host='0.0.0.0', port=9090)
index.html
<html>
<head>
<script language="Javascript">
var s = new WebSocket("ws://192.168.3.49:9090/foobar");
s.onopen = function() {
alert("connected !!!");
s.send("js send to server");
};
s.onmessage = function(e) {
alert("recv message")
var bb = document.getElementById('blackboard')
var html = bb.innerHTML;
bb.innerHTML = html + '<br/>' + e.data;
};
s.onerror = function(e) {
alert('error');
alert(e);
}
s.onclose = function(e) {
alert("connection closed");
}
function invia() {
var value = document.getElementById('testo').value;
alert(value);
s.send(value);
}
</script>
</head>
<body>
<h1>WebSocket</h1>
<input type="text" id="testo"/>
<input type="button" value="invia" onClick="invia();"/>
<div id="blackboard" style="width:640px;height:480px;background-color:black;color:white;border: solid 2px red;overflow:auto">
</div>
</body>
when I access http://ip:9090, I get the blow information:
connected !!!
recv message
connection closed
why websocket auto close? And occasionally there will be an error
[uwsgi-http key: 192.168.3.49:9090 client_addr: 192.168.3.1
client_port: 9177] hr_instance_read(): Connection reset by peer
[plugins/http/http.c line 646]
Seems like your are trying for echo gevent server. Example code
You need to keep the connection running by a loop. Change as following:
#ws.route('/foobar')
def echo(ws):
while True:
msg = ws.receive()
print(msg)
if msg is not None:
ws.send(msg)
else:
return
I am trying to set up a basic WSS websockets server. This is my minimal HTML (with the embedded javascript):
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Test</title>
</head>
<body style="background-color:white">
<h1>Test of WSS server</h1>
<p>Status: <span id=status"></span></p>
Click to send message
<script src="/newjs/jquery-2.1.1.js"></script>
<script>
var connection;
$(document).ready(function () {
window.WebSocket = window.WebSocket || window.MozWebSocket;
if (!window.WebSocket) {
alert("browser says no");
console.log("Browser does not supports websockets");
return;
}
setupConnection();
});
function message() {
var msg = "Test Message";
connection.send(msg);
}
function setupConnection() {
connection = new WebSocket('wss://www.example.com:14000');
connection.onerror = function(error) {
console.log('onerror fired');
};
connection.onopen = function(event) {
$("#status").html("Open");
};
connection.onmessage = function (message) {
alert(message.data);
};
}
setInterval(function() {
if (connection.readyState !== 1) {
setupConnection();
}
}, 5000);
</script>
</body>
</html>
The following is the JS server run by nodejs:
var fs=require("fs");
var ws_cfg = {
ssl: true,
port: 14000,
ssl_key: '/httpd/conf/ssl.key/my.key',
ssl_cert: '/httpd/conf/ssl.crt/my.crt',
ca_cert: '/httpd/conf/ssl.crt/gd_bundle-g2-g1.crt'
};
var processRequest = function(req, res) {
console.log("Request received.")
};
var httpServ = require('https');
var app = null;
app = httpServ.createServer({
key: fs.readFileSync(ws_cfg.ssl_key),
cert: fs.readFileSync(ws_cfg.ssl_cert),
ca: fs.readFileSync(ws_cfg.ca_cert),
},processRequest).listen(ws_cfg.port);
var WebSocketServer = require('ws').Server, ws_server = new WebSocketServer( {server: app});
ws_server.on('open',function(request) {
console.log("opening");
});
ws_server.on('request', function(request) {
console.log((new Date()) + ' Connection from origin ' + request.origin + '.');
if (request.origin!='https://www.example.com') {
console.log("rejecting request from " + request.origin + " as not coming from our web site");
return;
}
var connection = request.accept(null, request.origin);
connection.on('message', function(message) {
console.log("Got a message");
});
});
I fire up the server with node then load the web page in my browser (using either FF or Chrome). Using the developer tools I see that the connection appears to be made. On the server side I see the established connection using netstat. I also put an alert() in the browser side in the onopen() function and it fired.
The problem is that no console log output is produced. When connection.send(mag) is executed the on("message" event never appears to fire on the server. I'm at a loss here. I had this working as an http:// websocket server but this is my first attempt at wss:. I would appreciate any insight.
Notes:
The sever name is not example.com although that is what I show in my code.
The firewall is allowing anyone to connect on port 14000 using TCP protocol.
The cert is a working wildcard cert for the web site.
Finally figured out what it was after ignoring it for a month or so. It had to do with the symbolic link (/httpd) defined for the SSL files as in:
ssl_key: '/httpd/conf/ssl.key/my.key',
ssl_cert: '/httpd/conf/ssl.crt/my.crt',
They had to be changed to:
ssl_key: '/usr/local/apache2/conf/ssl.key/my.key',
ssl_cert: '/usr/local/apache2/conf/ssl.crt/my.crt',
Who knew that symbolic links were frowned upon? Well, now we all do.