I Have a simple setup witH a pytHon server running on a raspberry PI inside my Home network. On my PC I Have a basic HTML page witH some Javascript tHat sHould communicate witH tHe py server on my raspberry pi. THe server on tHe raspberry pi works perfect wHen tested from telnet on my PC.
Here is tHe PytHon code:
import socket
from time import*
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = ""
port = 51025
s.bind((host, port))
s.listen(1)
conn, addr = s.accept()
print "Connection open"
print conn, addr
while 1:
data = conn.recv(4096)
if data:
print "msg received"
conn.sendall(data +" 12 uniflu")
else:
print "connection lost"
s.listen(1)
conn, addr = s.accept()
print "Connection open"
print conn, addr
This is the javascript code:
window.onload = function() {
// Get references to elements on the page.
var form = document.getElementById('message-form');
var messageField = document.getElementById('message');
var messagesList = document.getElementById('messages');
var socketStatus = document.getElementById('status');
var closeBtn = document.getElementById('close');
var openBtn = document.getElementById('open');
// The rest of the code in this tutorial will go here...
// Create a new WebSocket.
var socket = new WebSocket('ws://192.168.0.81:51025');
// Close the WebSocket connection when the close button is clicked.
// Show a connected message when the WebSocket is opened.
socket.onopen = function(event) {
socketStatus.innerHTML = 'Connected to: ' + event.currentTarget.URL;
socketStatus.className = 'open';
};
// Handle any errors that occur.
socket.onerror = function(error) {
console.log('WebSocket Error: ' + error);
};
// Close the WebSocket connection when the close button is clicked.
closeBtn.onclick = function(e) {
e.preventDefault();
// Close the WebSocket.
socket.close();
return false;
};
// Show a disconnected message when the WebSocket is closed.
socket.onclose = function (event) {
var reason;
alert(event.code);
// See http://tools.ietf.org/html/rfc6455#section-7.4.1
if (event.code == 1000)
console.log( "Normal closure, meaning that the purpose for which the connection was established has been fulfilled.");
else if(event.code == 1001)
console.log("An endpoint is \"going away\", such as a server going down or a browser having navigated away from a page.");
else if(event.code == 1002)
console.log("An endpoint is terminating the connection due to a protocol error");
else if(event.code == 1003)
console.log("An endpoint is terminating the connection because it has received a type of data it cannot accept (e.g., an endpoint that understands only text data MAY send this if it receives a binary message).");
else if(event.code == 1004)
console.log("Reserved. The specific meaning might be defined in the future.");
else if(event.code == 1005)
console.log("No status code was actually present.");
else if(event.code == 1006)
console.log("The connection was closed abnormally, e.g., without sending or receiving a Close control frame");
else if(event.code == 1007)
console.log("An endpoint is terminating the connection because it has received data within a message that was not consistent with the type of the message (e.g., non-UTF-8 [http://tools.ietf.org/html/rfc3629] data within a text message).");
else if(event.code == 1008)
console.log("An endpoint is terminating the connection because it has received a message that \"violates its policy\". This reason is given either if there is no other sutible reason, or if there is a need to hide specific details about the policy.");
else if(event.code == 1009)
console.log("An endpoint is terminating the connection because it has received a message that is too big for it to process.");
else if(event.code == 1010) // Note that this status code is not used by the server, because it can fail the WebSocket handshake instead.
console.log("An endpoint (client) is terminating the connection because it has expected the server to negotiate one or more extension, but the server didn't return them in the response message of the WebSocket handshake. <br /> Specifically, the extensions that are needed are: " + event.reason);
else if(event.code == 1011)
console.log("A server is terminating the connection because it encountered an unexpected condition that prevented it from fulfilling the request.");
else if(event.code == 1015)
console.log("The connection was closed due to a failure to perform a TLS handshake (e.g., the server certificate can't be verified).");
else
console.log("Unknown reason");
$("#thingsThatHappened").html($("#thingsThatHappened").html() + "<br />" + "The connection was closed for reason: " + reason);
};
// Send a message when the form is submitted.
form.onsubmit = function(e) {
e.preventDefault();
// Retrieve the message from the textarea.
var message = messageField.value;
// Send the message through the WebSocket.
socket.send(message);
// Add the message to the messages list.
messagesList.innerHTML += '<li class="sent"><span>Sent:</span>' + message +
'</li>';
// Clear out the message field.
messageField.value = '';
return false;
};
// Handle messages sent by the server.
socket.onmessage = function(event) {
var message = event.data;
messagesList.innerHTML += '<li class="received"><span>Received:</span>' +
message + '</li>';
};
};
WHen I load tHe HTML page in my firefox browser, I can see tHe connection being made in pytHon by tHe printout, but after tHis tHe server becomes unresponsive. I also see tHe error message 1006 in tHe browser. Does anyone know tHis area and can Help me? WHy does it work very well from putty and not from tHe web browser?
Related
I'm trying to make a random system of connections. I have a button that initiates a connection and also looks for new peer for a new automatic call. But it is intermittent, sometimes it works perfect, sometimes I do not know anymore.
Backend - server.js
/** successful connection */
wss.on('connection', function (client) {
console.log("A new WebSocket client was connected.");
/** incomming message */
client.on('message', function (message) {
/** broadcast message to all clients */
var obj = JSON.parse(message);
if("callState" in obj) {
// New client, add it to the id/client object
// client.set('call_state') = 1
console.log("Recebeu mensagem!!!");
}else if("sdp" in obj || "ice" in obj) {
wss.broadcast(message, client);
}else{
console.log("Recebeu: "+message);
}
});
});
// broadcasting the message to all WebSocket clients.
wss.broadcast = function (data, exclude) {
console.log("Broadcasting message to all " + this.clients.length + " WebSocket clients.");
for(var i in this.clients) {
client = this.clients[i];
// don't send the message to the sender...
if (client === exclude) continue;
if (client.readyState === client.OPEN) client.send(data);
else console.error('Error: the client state is ' + client.readyState);
}
};
Frontend - webrtc.js
/** button START */
function start(isCaller) {
peerConnection = new RTCPeerConnection(peerConnectionConfig);
peerConnection.onicecandidate = gotIceCandidate;
peerConnection.addStream(localStream);
if ('ontrack' in peerConnection) {
// WebRTC Spec, Firefox
peerConnection.ontrack = ontrack
} else {
// Chrome, etc. This can be removed once all browsers support `ontrack`
peerConnection.onaddstream = gotRemoteStream
}
if(isCaller) {
peerConnection.createOffer().then(createdDescription).catch(errorHandler);
}
}
function gotMessageFromServer(message) {
if(!peerConnection) start(false);
var signal = JSON.parse(message.data);
// Ignore messages from ourself
if(signal.uuid == uuid) return;
if(signal.sdp) {
peerConnection.setRemoteDescription(new RTCSessionDescription(signal.sdp)).then(function() {
// Only create answers in response to offers
if(signal.sdp.type == 'offer') {
peerConnection.createAnswer().then(createdDescription).catch(errorHandler);
}
}).catch(errorHandler);
} else if(signal.ice) {
peerConnection.addIceCandidate(new RTCIceCandidate(signal.ice)).catch(errorHandler);
}
}
In the server log shows that every time I press the "Start" button it log 1 SDP message and 14 ICE messages
EDIT: Including error
When I call the "start" button for the first time, everything works. However, in the following calls sometimes only the audio feature remains and at other times without a new connection.
I was able to reproduce an error after clicking "Start" several times:
DOMException [InvalidStateError: "Cannot set remote answer in state
stable" code: 11 nsresult: 0x8053000b]
I have a local server running on: https://luisdemarchi.aplicativo.info:8091
I get the message from client but in case of replying message, i tried many ways but no result .
My JavaScript Code is
var eb = new EventBus("http://localhost:8080/loginUrl");
eb.onopen = function () {
console.log("Connection Open")
};
eb.onclose = function () {
console.log("Connection Close")
};
eb.registerHandler("server-to-client", function (message) {
console.log('received a message: ' + message.body());
});
// publish a message
function sendMes(message){
console.log("Sending Message "+message);
eb.send("client-to-server",message,function(callback){
console.log("Received Message "+callback)
});
}
My Java Server Code is
Router router = Router.router(vertx);
vertx.createHttpServer().requestHandler(router::accept).listen(8080);
SockJSHandler sockJSHandler = SockJSHandler.create(vertx);
BridgeOptions options = new BridgeOptions();
options.addInboundPermitted(new PermittedOptions().setAddress("client-to-server"));
options.addOutboundPermitted(new PermittedOptions().setAddress("server-to-client"));
sockJSHandler.bridge(options);
router.route("/loginUrl/*").handler(sockJSHandler);
EventBus eb = vertx.eventBus();
eb.consumer("client-to-server").handler(sockJSHand->{
System.out.println("Sending Message "+sockJSHand.body());//It prints the message from client
eb.send("server-to-client","Message");
});
How to reply back some message from server ?
Your code sample seems to be fine and almost looks like the chat server-client example application except that your should be using the EventBus#publish API instead of the EventBus#send API to allow the message to be dispatched among all registred handlers (all clients web browsers).
As per the Java docs:
EventBus publish(String address,
Object message)
Publish a message.
The message will be delivered to all handlers registered to the address.
An update of your server side code would be as follows:
Router router = Router.router(vertx);
vertx.createHttpServer().requestHandler(router::accept).listen(8080);
BridgeOptions options = new BridgeOptions();
options.addInboundPermitted(new PermittedOptions().setAddress("client-to-server"));
options.addOutboundPermitted(new PermittedOptions().setAddress("server-to-client"));
SockJSHandler sockJSHandler = SockJSHandler.create(vertx).bridge(options);
router.route("/loginUrl/*").handler(sockJSHandler);
EventBus eb = vertx.eventBus();
eb.consumer("client-to-server").handler(
sockJSHand -> {
System.out.println("Sending Message "+ sockJSHand.body());//It prints the message from client
eb.publish("server-to-client", "Message");
}
);
I've got a Java web application deployed on a local GlassFish 4.1 server that implements WebSockets to inter-operate with the web client. I'm able to successfully execute client-to-server communication over the socket, but server-to-client communication doesn't work for some reason.
The Java code that sends messages to the client:
try
{
String msg = ServerClientInteropManager.toResponseJSON(response);
parentSession.getBasicRemote().sendText(msg);
FLAIRLogger.get().info("Sent response to client. Message: " + msg);
}
catch (IOException ex) {
FLAIRLogger.get().error("Couldn't send message to session " + parentSession.getid() + ". Exception - " + ex.getMessage());
}
The Javascript code:
pipeline_internal_onMessage = function(event)
{
var msg = JSON.parse(event.data);
console.log("Received message from server. Data: " + event.data);
};
function pipeline_init()
{
if (PIPELINE !== null || PIPELINE_CONNECTED === true)
{
console.log("Pipline already initialized");
return false;
}
else
{
var pipelineURI = "ws://" + document.location.host + document.location.pathname + "webranker";
console.log("Attempting to establish connection with WebSocket # " + pipelineURI);
if ('WebSocket' in window)
PIPELINE = new WebSocket(pipelineURI);
else if ('MozWebSocket' in window)
PIPELINE = new MozWebSocket(pipelineURI);
else
{
console.log("FATAL: No WebSockets support");
alert("This browser does not support WebSockets. Please upgrade to a newer version or switch to a browser that supports WebSockets.");
return false;
}
// the other event listeners get added here
PIPELINE.onMessage = pipeline_internal_onMessage;
PIPELINE_CONNECTED = true;
window.onbeforeunload = function() {
pipeline_deinit();
};
console.log("Pipeline initialized");
return true;
}
}
The onMessage function is never fired, even when the server successfully calls the sendText() method. Using the AsyncRemote yields the same results. The onError listeners on both ends don't report anything either. This is my first time working with sockets so I might be missing something elementary.
replace
PIPELINE.onMessage = pipeline_internal_onMessage
with
PIPELINE.onmessage = pipeline_internal_onMessage
Please refer here for more.
var net = require('net');
var HOST = '0.0.0.0';
var PORT = 5000;
// Create a server instance, and chain the listen function to it
// The function passed to net.createServer() becomes the event handler for the 'connection' event
// The sock object the callback function receives UNIQUE for each connection
net.createServer(function(sock) {
// We have a connection - a socket object is assigned to the connection automatically
console.log('CONNECTED: ' + sock.remoteAddress +':'+ sock.remotePort);
// Add a 'data' event handler to this instance of socket
sock.on('data', function(data) {
console.log('DATA ' + sock.remoteAddress + ': ' + data);
// Write the data back to the socket, the client will receive it as data from the server
if (data === "exit") {
console.log('exit message received !')
}
});
// Add a 'close' event handler to this instance of socket
sock.on('close', function(data) {
console.log('CLOSED: ' + sock.remoteAddress +' '+ sock.remotePort);
});
}).listen(PORT, HOST);
console.log('Server listening on ' + HOST +':'+ PORT);
No matter what I try, I cannot get:
if (data === "exit") {
console.log('exit message received !')
}
working, it's always false.
I'm connecting via telnet and sending "exit", the server should then go into the "if" loop and say "exit message received". This never happens, can someone shed some light ? thanks
That's because data is not a string, if you try to compare with === you will get false because types don't match.
To solve it you should compare the data object with a simple == or use socket.setEncoding('utf8') previous to binding the data event.
https://nodejs.org/api/net.html#net_event_data
var net = require('net');
var HOST = '0.0.0.0';
var PORT = 5000;
net.createServer(function(sock) {
console.log('CONNECTED:',sock.remoteAddress,':',sock.remotePort);
sock.setEncoding("utf8"); //set data encoding (either 'ascii', 'utf8', or 'base64')
sock.on('data', function(data) {
console.log('DATA',sock.remoteAddress,': ',data,typeof data,"===",typeof "exit");
if(data === "exit") console.log('exit message received !');
});
}).listen(PORT, HOST, function() {
console.log("server accepting connections");
});
Note.
If the data received is going to be big you should concatenate and handle the message comparison at the end of it. Check other questions to handle those cases:
Node.js net library: getting complete data from 'data' event
I am aware this is quite an old post, when I tried to implement the code in the answer to this question I came across the same problem regardless of having used "==" or utf8 encoding. The issue for me turned out to be that the client I was using was appending a '\n' character to the end of the exit message thus causing the string comparison to fail on the server. Perhaps this is not an issue with telnet and the like but this was the case with netcat. Hopefully this sheds some light for anyone else who comes across this post and has the same problem that I did.
I am bit new in CGI programming, and I trying to make an online chat API but face not few troubles:
I was looking online for solution and found Websocket for client (js) and HTTP::Daemon for perl, but I have no idea where to start to make the server listen for the connections from the browser.
Here is my JavaScript code:
ws = new WebSocket('ws://www.crazygao.com:3000'); // test
ws.onopen = function() {
alert('Connection is established!'); // test
};
ws.onclose = function() {
alert('Connection is closed');
};
ws.onmessage = function(e) {
var message = e.data;
//alert('Got new message: ' + message);
};
ws.onerror = function(e) {
//var message = e.data;
alert('Error: ' + e);
};
Here is my Perl script test code:
use HTTP::Daemon;
use HTTP::Status;
my $d = HTTP::Daemon->new(
LocalAddr => 'www.crazygao.com',
LocalPort => 3000
) || die; print "Please contact me at: <URL:", $d->url, ">\n";
while(my $c = $d->accept) {
$c->send_response("1"); # test
while (my $r = $c->get_request) {
if ($r->method eq 'GET') {
$c->send_response("...");
}
}
$c->close;
undef($c);
}
When the page loads, the connection closing immediately, and in Chrome console window I see the following error:
WebSocket connection to 'ws://198.38.89.14:3000/' failed: Error in connection establishment: net::ERR_CONNECTION_REFUSED
I run the perl script manually (using simple call to http://example.com/cgi-bin/xxx.cgi) and then when I refresh the page I get:
WebSocket connection to 'ws://198.38.89.14:3000/' failed: Error during WebSocket handshake: Unexpected response code: 200
I understand that the server normally returns 200 when OK, but Websocket is waiting for 101 code as "OK".
My question is, if so, how can I achieve this?
I know this is old and I got here because I was looking for an answer myself. I ended up finding the answer myself by using Net::WebSocket::Server.
http://search.cpan.org/~topaz/Net-WebSocket-Server-0.003004/lib/Net/WebSocket/Server.pm for more details on how to use the module and example.
Basically, you'll have this perl code to match your javascript (copied and modified from the CPAN page of Net::WebSocket::Server):
use Net::WebSocket::Server;
my $origin = 'http://www.crazygao.com';
Net::WebSocket::Server->new(
listen => 3000,
on_connect => sub {
my ($serv, $conn) = #_;
$conn->on(
handshake => sub {
my ($conn, $handshake) = #_;
$conn->disconnect() unless $handshake->req->origin eq $origin;
},
utf8 => sub {
my ($conn, $msg) = #_;
$_->send_utf8($msg) for $conn->server->connections;
},
binary => sub {
my ($conn, $msg) = #_;
$_->send_binary($msg) for $conn->server->connections;
},
);
},
)->start;