Websocket server connection from javascript client gives net::ERR_CONNECTION_REFUSED - javascript

My domain :: https://example.com
My web socket server code path :: http://live.example.com
My php client path:: http://live.example.com/client-php
My JS client path :: http://live.example.com/client-web
I have my php websocket server running as follows
<?php
namespace App;
use Ratchet\Server\IoServer;
use Ratchet\Http\HttpServer;
use Ratchet\WebSocket\WsServer;
require_once './controllers/SocketController.php';
require './vendor/autoload.php';
// configurations
$server = IoServer::factory(
new HttpServer(
new WsServer(
new SocketController()
)
),
8585 // the port of the web socket // I TIRED 8080,8181 also
);
$server->run();
I have two client, one is php-client , which connects to socket as follows
\Ratchet\Client\connect('ws://127.0.0.1:8585')->then(function($conn) {
$conn->send(
json_encode(array(
"to" => "34366",
"data" => "Hello World",
))
);
$conn->close();
}, function ($e) {
$this->logger->info("Can not connect: {$e->getMessage()}");
});
After above code is run , websocket connection is successful ,i can see new connection logs from my socketcontroller as follows :
New connection! (51) Connection 51 has disconnected
Next I have one javascript web client also that connects to same web socket as follows
var socket = new WebSocket('ws://localhost:8585');
socket.onopen = function (event) {
log.append('Conect to server <br>');
socket.send('{ "connect": "1", "id": "34366" }');
};
But on running the web client console give below error always
index.js:2 WebSocket connection to 'ws://localhost:8585/' failed: Error in connection establishment: net::ERR_CONNECTION_REFUSED
(anonymous) # index.js:2
Do below line have issue ??
new WebSocket('ws://localhost:8585');
I tried giving paths for 127.0.0.1, localhost, domain , socketserver path also , but same errors always.
Please help!!

Related

error when trying to connect to python socket using websocket javascript client

I am trying to make a connection from my javascript client in a browser to my python server and to send data from the server to the client, but when trying to connect I get the error: failed: Error in connection establishment: net::ERR_CONNECTION_REFUSED
I tried using wss instead of ws.
I also tried using socket.io instead of websocket, which wasn't helping either. I don't remember all the things I tried but none of them helped.
Javascript client:
var conn = new WebSocket('ws://localhost:2001');
conn.onmessage = function (event) {
console.log(event.data);
Python server:
# Echo server program
import socket
HOST = 'localhost'
PORT = 2001
def sendSensorData(data):
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind(HOST, PORT)
s.listen(1)
conn, addr = s.accept()
with conn:
print('Connected by', addr)
while True:
print(data)
message = str(data).encode()
try:
# if not data: break
conn.sendall(message)
except BaseException as e:
print (e)
Edit: This is the error from python:
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/threading.py", line 917, in _bootstrap_inner
self.run()
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/threading.py", line 865, in run
self._target(*self._args, **self._kwargs)
File "/Users/joep/Documents/GitHub/Walnut-installation-web-app/testAPI/workers/sensorStream.py", line 26, in sensorStream
sendSensorData.sendSensorData(data)
File "/Users/joep/Documents/GitHub/Walnut-installation-web-app/testAPI/functions/sendSensorData.py", line 19, in sendSensorData
conn.send(message)
BrokenPipeError: [Errno 32] Broken pipe
Hopefully it is a simple trick to fix it.

Handshake error with WebSocket python server and JS client

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()

web socket not working with SSL and WSS in javascript

I have implemented web socket using below code,
try {
console.log('wss://' + hostname + ':' + port + endpoint);
webSocket = new WebSocket(webSocketURL);
webSocket.onmessage = function (event) {
//console.log('send message successfully.');
var obj = JSON.parse(event.data);
append_data(obj, market_pair);
};
} catch (exception) {
console.log('Exception handle!');
console.error(exception);
}
My page is https supported so I am using wss protocol. but issue is it gives me error that "Firefox can’t establish a connection to the server at wss://domainname.com:4008/order.php"
if I will load the page using simple http and use ws in websocket then it is working fine but with wss it shows above error. same way in google chrome it will also not able to connect.
My ssl certificate is installed correctly in server and my hosting and domain provided in godaddy and they told me that certificate is installed correctly.
I am running server side socket in php and it is working fine just now able to connect to that socket port using wss://
I have found that I am not able to do handshak using my php code because my php file is running in background and the content I am getting by socket read is encrypted.
function doHandshake($received_header, $client_socket_resource, $host_name, $port) {
echo $received_header;
$headers = array();
$lines = preg_split("/\r\n/", $received_header);
foreach ($lines as $line) {
$line = chop($line);
if (preg_match('/\A(\S+): (.*)\z/', $line, $matches)) {
$headers[$matches[1]] = $matches[2];
}
}
$secKey = $headers['Sec-WebSocket-Key'];
echo $headers['Sec-WebSocket-Key'];
$secAccept = base64_encode(pack('H*', sha1($secKey . '258EAFA5-E914-47DA-95CA-C5AB0DC85B11')));
//$secAccept = base64_encode(sha1($secKey . '258EAFA5-E914-47DA-95CA-C5AB0DC85B11'));
$buffer = "HTTP/1.1 101 Web Socket Protocol Handshake\r\n" .
"Upgrade: websocket\r\n" .
"Connection: Upgrade\r\n" .
"WebSocket-Origin: $host_name\r\n" .
"WebSocket-Location: wss://$host_name:$port/websocket/btc_boon_pair.php\r\n" .
"Sec-WebSocket-Accept:$secAccept\r\n\r\n";
socket_write($client_socket_resource, $buffer, strlen($buffer));
}
this is my handshak function $headers['Sec-WebSocket-Key'] is undefined because $received_header is encrypted.
can anyone suggest the solution of this issue? I have to run php file as daemon and want to connect using wss protocol.
Ok finally I solved the issue.
due to the SSL encryption it is not able to read socket in my php daemon file. So I get solution from below answer
https://serverfault.com/questions/804862/apache-mod-proxy-forward-secure-websocket-to-non-secure
we can use proxy pass in apache so it will send all request with /websocket to the other ws://host:port/
after this it is working perfectly.
Also make sure that domain name is not using proxy because due to that my above solution is not worked but After removing proxy from DNS settings it started working.
In my case, I was using a VPS on Dreamhost.com and thus couldn't change Apache configuration files. However, I used this library to start secure socket server via following code:
use WSSC\Components\ServerConfig;
use WSSC\WebSocketServer;
$config = new ServerConfig();
$config->setIsSsl(true)->setAllowSelfSigned(true)
->setCryptoType(STREAM_CRYPTO_METHOD_SSLv23_SERVER)
->setLocalCert("./tests/certs/cert.pem")->setLocalPk("./tests/certs/key.pem")
->setPort(8888);
$websocketServer = new WebSocketServer(new ServerHandler(), $config);
$websocketServer->run();
I filled cert.pem and key.pem files with proper values from Dreamhost dashboard -> Websites -> Secure Certificates section.

Sample JavaScript can't connect to Ruby WebSocket server

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.

Firefox Nodejs Websocket

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).

Categories

Resources