i have python server(with the help of asyncio and websockets module) and js client(with the help of websockets library) that are connected. The problem is that i need this connection to be secured (i'm working on passwords), but i had no success on establishing a connection with wss(web socket secure) - the code runs only with ws.
I even tried to establish my own encryption with RSA and AES but that also didn't work.
i'm really hopeles about it so if anyone ever did it or know a little about it, pls help me figure out what's wrong with it, or a direction to a rigth solution for secured connection that will work.
here's my server:
async def app(websocket, path):
while True :
data = await websocket.recv()
if (data== "close"):
print("connection with client closed.")
break
data = data.encode()
arr = data.split("~".encode())
for i in range(0,4):
arr[i]=arr[i].decode()
resualt=algo(arr)
await websocket.send(resualt)
start_server = websockets.serve(app, '0.0.0.0', 6169)
and my client:
var socket = new WebSocket("ws://127.0.0.1:6169/");
socket.onopen = function (evt) {
socket.send(st);
};
socket.onmessage = function (evt) {
alert("scrool extension page down to see the password");
$('#res').val(evt.data);
socket.send("close");
};
socket.onerror = function (evt) {
alert("the error is: "+evt.data);
};
in the python script we tried to use ssl:
c = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
c.load_default_certs(purpose=ssl.Purpose.CLIENT_AUTH)
start_server = websockets.serve(app, '0.0.0.0', 6169, ssl=c)
and in the js sciprt we wrote instead of the ws, wss:
"ws://127.0.0.1:6169/")
and the error we get:
WebSocket connection to 'wss://127.0.0.1:6169/' failed: Error in connection
establishment: net::ERR_CONNECTION_CLOSED
Related
I have been trying to setup a wss server using nodejs, and have encountered a problem when trying to connect to it using chrome. The problem still occurs with all extensions disabled and in an incognito window so I've ruled that out as the problem.
When trying to connect using chrome, I get the error:
WebSocket connection to 'wss://www.domain-name.com/' failed:
with no reason given. On the server, socket.on('close') is called immediately with description "Connection dropped by remote peer" The close event has wasClean = false. This error does not occur when connecting from safari and Firefox so I'm not really sure where to look to see what's causing it. It's running on AWS Lightsail, and through an Apache proxy server.
The client code:
var socket = new WebSocket("wss://www.domain-name.com", 'JSON')
socket.onopen = function (event) {
console.log('open');
socket.send('socket opened')};
socket.onclose = function (event) {
console.log(event)};
socket.onmessage = function(message) {
console.log('receiving message from server...')};
And the server code:
const WebSocketServer = require('websocket').server;
app = express()
var server = app.listen(3000, () => {
console.log('Server started');
});
app.use(express.static('public'));
var wsServer = new WebSocketServer({
httpServer: server
});
wsServer.on('request', function(request){
console.log('New connection');
var connection = request.accept(null, request.origin);
connection.send('welcome from server...');
connection.on('message', function(message){
console.log(message)};
connection.on('close', function(reasonCode, description) {
console.log('disconnecting', reasonCode, description);
});
});
I also got the same error before switching to a secure WebSocket server. Any help would be appreciated, I've run out of places to look and ways to try and get more information to help out what the problem is.
EDIT: it seems to work on chrome on my phone, but not on chrome on my friends phone?
The problem was not specifying the protocol when accepting the connection. After about 20 hours working on the same bug and implementing an SSL certificate to get it to work, I changed:
request.accept(null, request.origin);
to:
request.accept('json', request.origin);
For some reason the chrome gives a really unhelpful error message. Microsoft edge the same error occurs, but gives a much more helpful error message so I could work out what was going on.
In my case, this was caused by passing an unused options value as the third parameter to the WebSocket constructor. The options parameter is supported by Node.js's ws module but not by browsers; however, instead of displaying a clean error message, Chrome closed the connection without a good description.
I would like to conenct an MQTT broker with Javascript in order to subscript to a topic and publish messages. The connection needs to be done through tcp on port 1883. I am using MQTT.js library. The front end is in angularjs.
The example followed is the one in MQTT.js page, though the connection cannot be achieved. Could anyone please help?
Connection through index.html:
<script src="../node_modules/mqtt/browserMqtt.js"></script>
Code for connection:
var client = mqtt.connect('url.com:1883',{clientId :'client1', clean: true});
client.on('connect', function () {
console.log("onsubscribe");
client.subscribe('votingSignals', function (err) {
if (!err) {
console.log("onsubscribe");
client.publish('votingSignals', 'start')
}
})
})
client.on('message', function (topic, message) {
// message is Buffer
console.log(message.toString())
client.end()
})
The error displayed is:
WebSocket connection to 'ws://url.com:1883/' failed: Error during WebSocket handshake: net::ERR_CONNECTION_RESET
From a web browser you can ONLY use MQTT over Websockets, not native MQTT (over TCP).
This is because the browser will not let you open a normal socket.
I am trying to setup a communication between a python script (that will do a lot of computation on data that cannot be done in javascript and send send that data as a json) and a javascript client.
I have the following code for my python server:
import socket
import sys
from thread import *
HOST = '' # Symbolic name meaning all available interfaces
PORT = 9888 # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print 'Socket created'
#Bind socket to local host and port
try:
s.bind((HOST, PORT))
except socket.error as msg:
print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
sys.exit()
print 'Socket bind complete'
#Start listening on socket
s.listen(10)
print 'Socket now listening'
#Function for handling connections. This will be used to create threads
def clientthread(conn):
#Sending message to connected client
conn.send('Welcome to the server. Type something and hit enter\n') #send only takes string
#infinite loop so that function do not terminate and thread do not end.
while True:
#Receiving from client
data = conn.recv(1024)
reply = 'OK...' + data
if not data:
break
conn.sendall(reply)
#came out of loop
conn.close()
#now keep talking with the client
while 1:
#wait to accept a connection - blocking call
conn, addr = s.accept()
print 'Connected with ' + addr[0] + ':' + str(addr[1])
#start new thread takes 1st argument as a function name to be run, second is the tuple of arguments to the function.
start_new_thread(clientthread ,(conn,))
s.close()
And the following code for my javascript client:
var connection = new WebSocket('ws://127.0.0.1:8999');
connection.onopen = function () {
connection.send('Hello'); // Send the message to the server
};
I get the following error from my javascript client:
Error during WebSocket handshake: net::ERR_INVALID_HTTP_RESPONSE
And the following output from my python server
Socket created
Socket bind complete
Socket now listening
Connected with 127.0.0.1:53956
Unhandled exception in thread started by <function clientthread at 0x10abac578>
Traceback (most recent call last):
File "server.py", line 71, in clientthread
data = conn.recv(1024)
socket.error: [Errno 54] Connection reset by peer
Would anyone know what is wrong?
Edit: forgot to mention that I have seen this SO Post before, but my problem is not the same, or rather should I say that the error encountered by OP is not the same as mine.
A WebSocket is a not the same as a plain TCP socket you create. WebSocket is a protocol on top of TCP instead which starts with a HTTP handshake and then continues with a framing based protocol. If you want to implement a WebSocket server in Python you need to implement this protocol as specified in RFC 6455 or use existing WebSocket libraries.
An example server-side python code using WebSocket is:
import asyncio
import websockets
async def handle_message(message):
print(message)
async def consumer_handler(websocket, path):
while True:
message = await websocket.recv()
await handle_message(message)
start_server = websockets.serve(consumer_handler, 'localhost', 8765)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
I would like to fiddle with websockets a bit. I installed a Ruby gem called "websocket-ruby" (https://github.com/imanel/websocket-ruby) I started a pry / IRB session and typed:
require "websocket"
#handshake = WebSocket::Handshake::Server.new(:host => "localhost", :port => 8080,:secure=>true)
This starts a websocket server as far as I know. Then I opened in my browser the Javascript HTML page which attempt to connect to the server:
<!doctype html>
<html lang="en">
<head>
<title>Websocket Client</title>
</head>
<body>
<script>
var exampleSocket = new WebSocket("wss://localhost:8080");
exampleSocket.onopen = function (event) {
exampleSocket.send("Can you hear me?");
};
exampleSocket.onmessage = function (event) {
console.log(event.data);
}
</script>
</body>
</html>
But it says in the console log:
failed: Error in connection establishment: net::ERR_CONNECTION_REFUSED
I tried different ports both in server and in the client respectively: 8081, 12345, but I always get this error message.
I have some idea about websocket and javascript, but not websocket-ruby.
I hope it will helpful you.
In nodejs.. server.js file, write below code
var WebSocketServer = require("ws").Server;
var wss = new WebSocketServer({port:8100});
console.log("websocket Server is Running...");
wss.on('connection', function connection(ws) {
// Store the remote systems IP address as "remoteIp".
var remoteIp = ws.upgradeReq.connection.remoteAddress;
// Print a log with the IP of the client that connected.
console.log('Connection received: ', remoteIp);
// Add a listener which listens for the "message" event.
// When a "message" event is received, take the contents
// of the message and pass it to the broadcast() function.
ws.on('message', wss.broadcast);
});
wss.broadcast = function(msg) {
wss.clients.forEach(function each(client) {
client.send(msg);
})
};
In javascript...
var SERVER_URL = 'ws://localhost:8100';
//instead of localhost you can also use IP address of your system
var ws;
function connect() {
alert('connect');
ws = new WebSocket(SERVER_URL, []);
// Set the function to be called when a message is received.
ws.onmessage = handleMessageReceived;
// Set the function to be called when we have connected to the server.
ws.onopen = handleConnected;
// Set the function to be called when an error occurs.
ws.onerror = handleError;
}
function handleMessageReceived(data) {
// Simply call logMessage(), passing the received data.
logMessage(data.data);
}
function handleConnected(data) {
// Create a log message which explains what has happened and includes
// the url we have connected too.
var logMsg = 'Connected to server: ' + data.target.url;
// Add the message to the log.
logMessage(logMsg)
}
function handleError(err) {
// Print the error to the console so we can debug it.
console.log("Error: ", err);
}
function logMessage(msg) {
// with the new message.
console.log(msg);
}
/** This is the scope function that is called when a users hits send. */
function sendMessage{
ws.send(msg);
};
connect();
in html use one button to send message to websocket server
<button onclick="sendMessage('Hi Websocket')">send message</button>
To the best of my knowledge, the Ruby code you presented does not start a Websocket server... what it does is initiate a server-side parser.
To start a server you need to use an actual websocket server.
ActionCable (with Rails) uses the websocket-ruby library to parse websocket events and it uses nio4r to operate the actual server.
Faye have a similar solution and em-websockets use the websocket-ruby gem with EventMachine.
Other Ruby Websocket servers include Iodine, which uses the C library facil.io. Iodine is used by the framework plezi as well as independently.
Since you were trying to run an echo server, here's a quick example using the Plezi framework (you can use it as middleware in Sinatra or Rails)...
...place the following in a config.ru file:
require 'plezi'
class WebsocketSample
# HTTP index
def index
'Hello World!'
end
# called when Websocket data is recieved
#
# data is a string that contains binary or UTF8 (message dependent) data.
def on_message(data)
puts "Websocket got: #{data}"
write data
end
end
Plezi.route '/', WebsocketSample
run Plezi.app
To run the server, call (ignore the $ sign, it marks this code as terminal code):
$ iodine
notice: Iodine requires a BSD / Unix / Linux machine, such as macOS, Ubuntu, etc'. It won't work on windows.
I am using Aurora 17, Chrome 22 and Firefox 16 and I am trying to create a simple chat app. I am using Node 0.8.9.
Firefox is getting the error that it cannot connect giving the error
Firefox can't establish a connection to the server at ws://localhost/.
I also tried it with the port and it have the same message
Firefox can't establish a connection to the server at ws://localhost:4444/.
Here is my code:
Server Code:
var http = require('http');
var net = require('net');
function onRequest(req, res) {
// Does enough to render a page and javascript
}
http.createServer(onRequest).listen(4444);
var socket = new net.Socket();
socket.connect(4444, "localhost", function(){
console.log("Socket Connected");
});
socket.on("message", function(message){
console.log(message);
});
Client Code:
var WebSocket = window.WebSocket || window.MozWebSocket;
var connection = new WebSocket('ws://localhost:4444');
connection.onopen = function() {
// Never runs
alert("This never runs :(")
}
connection.onerror = function(error) {
// Always runs here
console.log(error)
}
I get an output that the Socket is connect from the log statement on the server but Firefox cannot connect to the socket.
On Chrome, there is no error but the "onopen" is never fired. Using connection.send("a message") does not send anything to the server and returns false.
You're creating an ordinary TCP client socket in your server code and connecting it to your HTTP server. That's not at all the same thing as creating a WebSocket server that a browser can connect to. Use a library designed for the purpose (socket.io is very commonly used, since it can fall back to alternate transports when a browser doesn't support WebSockets).