Web socket connection can't be established - html

I am able to establish connection between browser and server lately.. But for the past two days the connection is not getting established.. I am unable to figure out what could have gone wrong?
<head>
<script type="text/javascript">
function WebSocketTest()
{
if ("WebSocket" in window)
{
var x=document.getElementById('chat').value;
// Let us open a web socket
var ws = new WebSocket("ws://localhost:7869/echo");
ws.onopen = function()
{
// Web Socket is connected, send data using send()
ws.send(x);
var send=document.getElementById('fill');
send.innerHTML = send.innerHTML+'<br>'+ x;
};
ws.onmessage = function (evt)
{
var received_msg = evt.data;
var send=document.getElementById('fill');
send.innerHTML = send.innerHTML +'<br>'+ received_msg;
};
ws.onclose = function()
{
// websocket is closed.
alert("Connection is closed...");
};
}
else
{
// The browser doesn't support WebSocket
alert("WebSocket NOT supported by your Browser!");
}
}
</script>
</head>
<body>
<div id="sse">
<input type="text" id="chat"></div><br>
<button type='submit' onclick='javascript:WebSocketTest()'>Send</button>
<div id='fill'>hi</div>
</body>
Here is the code and websocket server is listening the 7869 port.

Related

send audio using html5 websockets

My requirement is to send audio chunks captured from microphone to the server using html5 web socket connection.
Establish a web socket connection with the server.When user is speaking capture small chunks of audio and send to the server. This should happen till the user stops speaking for 10 seconds, then close the web socket connection. Again open the web socket connection when user starts speaking.
I know how to open a connection and send the audio for the first time.
I have two buttons. onClick of one button(startRecording) i will open web socket connection and i am recording the audio.
onClick of second button(stopRecording) i am sending the audio to the server.
But my problem is how to do this with out buttons and it has to record the audio till user pause and send to the server.
window.URL = window.URL || window.webkitURL;
navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
var recorder;
var audio = document.querySelector('audio');
var websocket ;
var text;
var onSuccess = function(s) {
var context = new AudioContext();
var mediaStreamSource = context.createMediaStreamSource(s);
recorder = new Recorder(mediaStreamSource);
recorder.record();
// audio loopback
// mediaStreamSource.connect(context.destination);
}
function startRecording() {
var wsURI = "url";
websocket = new WebSocket(wsURI);
websocket.onopen = function(evt) {
onOpen(evt)
};
websocket.onclose = function(evt) { onClose() };
websocket.onmessage = function(evt) { onMessage(evt) };
websocket.onerror = function(evt) { onError(evt) };
function onOpen(evt) {
var message = {
'action': 'start',
//'content-type': 'audio/l16;rate=22050'
'content-type': 'audio/wav;rate=22050'
};
websocket.send(JSON.stringify(message));
}
function onMessage(evt) {
console.log(evt.data);
//console.log(JSON.parse(evt.data))
}
}
function onClose() {
websocket.close();
}
if (navigator.getUserMedia) {
navigator.getUserMedia({audio: true}, onSuccess, onFail);
} else {
console.log('navigator.getUserMedia not present');
}
}
function stopRecording() {
recorder.stop();
recorder.exportWAV(function(s) {
//audio.src = window.URL.createObjectURL(s);
websocket.send(s);
//websocket.onclose();
});
}

Receiving "Error: InvalidStateError: DOM Exception 11" on HTML5 websocket when calling .send(data) using Node.js

I am currently trying to develop a small chat application using node.js. This is my first node project but I am getting an error and I'm not really sure how to solve it.
I have written a simple chat server in node which is below.
var port = 3000;
var net = require('net');
var clients = [];
var server = net.createServer(function (socket) {
clients.push(socket);
bindEventHandlers(socket);
});
setInterval(function(){
console.log(clients.length);
}, 2000);
server.listen(port);
console.log('Server is listening on localhost:' + port);
function bindEventHandlers(socket) {
socket.on('data', function(data){
broadcastDataToAllClient(data, socket);
});
socket.on('close', function(){
clients.splice(clients.indexOf(socket), 1);
});
socket.on('error', function(){
console.log('Known Error << "It\'s a feature!"');
})
}
function broadcastDataToAllClient(data, socket) {
for (var client in clients) {
if(clients[client] == socket){ continue; }
clients[client].write(data);
}
}
And a quick client interface
<!DOCTYPE HTML>
<html>
<head>
<title>Node.js Chat Server</title>
<script type="text/javascript">
function init(){
if (window.WebSocket) {
var input = document.getElementById('messageBox');
var webSocket = new WebSocket("ws://localhost:3000/");
input.onkeyup = function(e){
if(e.keyCode == 13) {
console.log('sending message');
webSocket.send('some data');
}
};
webSocket.onopen = function(e){
alert('Open');
}
webSocket.onmessage = function(e){
console.log('Message');
}
webSocket.onclose = function(e){
console.log('Close');
}
webSocket.onerror = function(e){
console.log('Error');
}
} else {
console.log('unable to support :(');
}
}
</script>
</head>
<body lang="en" onload="init();">
<h1>Node.js Chat Server</h1>
<h3>Welcome to this simple chat server!</h3>
<input id="messageBox" size="50" />
</body>
</html>
When I call the webSocket.send('some data') I receive this error Error: InvalidStateError: DOM Exception 11. In the chat-server code I have a loop which logs the number of current clients so I know that the browser is connected.
Not sure where to go from here and any help would be much appreciated.
Alex
When you do webSocket.send('some data') the socket connection must be established, or specifically socket.readyState == 1.
You can check the websocket events here. To make sure this never happens, you should send after connection open, by using Socket.onopen event handler. You can do it like this.
if(webSocket.readyState == 1){
webSocket.send('some data');
}
else{
webSocket.onopen = function(e){
webSocket.send('some data');
}
}

Video Conferencing in HTML5: WebRTC via Socket.io

I'm trying to implement this video conferencing HTML5 application. I'm not sure exactly what is going on but I followed the instructions, maybe I missed something...
I copied the HTML file (index.html) with the socket IP changed to the correct one for my server:
<!DOCTYPE html>
<html>
<head>
<title>WebRTC Demo</title>
</head>
<body>
<h1>WebRTC Demo using Socket.IO</h1>
<video id="webrtc-sourcevid" autoplay style="width: 320px; height: 240px; border: 1px solid black;"></video>
<button type="button" onclick="startVideo();">Start video</button>
<button type="button" onclick="stopVideo();">Stop video</button>
<video id="webrtc-remotevid" autoplay style="width: 320px; height: 240px; border: 1px solid black;"></video>
<button type="button" onclick="connect();">Connect</button>
<button type="button" onclick="hangUp();">Hang Up</button>
<p>Run a node.js server and adapt the address in the code.</p>
<script src="http://cdn.socket.io/stable/socket.io.js"></script>
<script>
// create socket
var socket = io.connect('localhost:1337/');
var sourcevid = document.getElementById('webrtc-sourcevid');
var remotevid = document.getElementById('webrtc-remotevid');
var localStream = null;
var peerConn = null;
var started = false;
var channelReady = false;
var mediaConstraints = {'mandatory': {
'OfferToReceiveAudio':true,
'OfferToReceiveVideo':true }};
var isVideoMuted = false;
// get the local video up
function startVideo() {
navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || window.navigator.mozGetUserMedia || navigator.msGetUserMedia;
window.URL = window.URL || window.webkitURL;
navigator.getUserMedia({video: true, audio: true}, successCallback, errorCallback);
function successCallback(stream) {
localStream = stream;
if (sourcevid.mozSrcObject) {
sourcevid.mozSrcObject = stream;
sourcevid.play();
} else {
try {
sourcevid.src = window.URL.createObjectURL(stream);
sourcevid.play();
} catch(e) {
console.log("Error setting video src: ", e);
}
}
}
function errorCallback(error) {
console.error('An error occurred: [CODE ' + error.code + ']');
return;
}
}
// stop local video
function stopVideo() {
if (sourcevid.mozSrcObject) {
sourcevid.mozSrcObject.stop();
sourcevid.src = null;
} else {
sourcevid.src = "";
localStream.stop();
}
}
// send SDP via socket connection
function setLocalAndSendMessage(sessionDescription) {
peerConn.setLocalDescription(sessionDescription);
console.log("Sending: SDP");
console.log(sessionDescription);
socket.json.send(sessionDescription);
}
function createOfferFailed() {
console.log("Create Answer failed");
}
// start the connection upon user request
function connect() {
if (!started && localStream && channelReady) {
createPeerConnection();
started = true;
peerConn.createOffer(setLocalAndSendMessage, createOfferFailed, mediaConstraints);
} else {
alert("Local stream not running yet - try again.");
}
}
// stop the connection upon user request
function hangUp() {
console.log("Hang up.");
socket.json.send({type: "bye"});
stop();
}
function stop() {
peerConn.close();
peerConn = null;
started = false;
}
// socket: channel connected
socket.on('connect', onChannelOpened)
.on('message', onMessage);
function onChannelOpened(evt) {
console.log('Channel opened.');
channelReady = true;
}
function createAnswerFailed() {
console.log("Create Answer failed");
}
// socket: accept connection request
function onMessage(evt) {
if (evt.type === 'offer') {
console.log("Received offer...")
if (!started) {
createPeerConnection();
started = true;
}
console.log('Creating remote session description...' );
peerConn.setRemoteDescription(new RTCSessionDescription(evt));
console.log('Sending answer...');
peerConn.createAnswer(setLocalAndSendMessage, createAnswerFailed, mediaConstraints);
} else if (evt.type === 'answer' && started) {
console.log('Received answer...');
console.log('Setting remote session description...' );
peerConn.setRemoteDescription(new RTCSessionDescription(evt));
} else if (evt.type === 'candidate' && started) {
console.log('Received ICE candidate...');
var candidate = new RTCIceCandidate({sdpMLineIndex:evt.sdpMLineIndex, sdpMid:evt.sdpMid, candidate:evt.candidate});
console.log(candidate);
peerConn.addIceCandidate(candidate);
} else if (evt.type === 'bye' && started) {
console.log("Received bye");
stop();
}
}
function createPeerConnection() {
console.log("Creating peer connection");
RTCPeerConnection = webkitRTCPeerConnection || mozRTCPeerConnection;
var pc_config = {"iceServers":[]};
try {
peerConn = new RTCPeerConnection(pc_config);
} catch (e) {
console.log("Failed to create PeerConnection, exception: " + e.message);
}
// send any ice candidates to the other peer
peerConn.onicecandidate = function (evt) {
if (event.candidate) {
console.log('Sending ICE candidate...');
console.log(evt.candidate);
socket.json.send({type: "candidate",
sdpMLineIndex: evt.candidate.sdpMLineIndex,
sdpMid: evt.candidate.sdpMid,
candidate: evt.candidate.candidate});
} else {
console.log("End of candidates.");
}
};
console.log('Adding local stream...');
peerConn.addStream(localStream);
peerConn.addEventListener("addstream", onRemoteStreamAdded, false);
peerConn.addEventListener("removestream", onRemoteStreamRemoved, false)
// when remote adds a stream, hand it on to the local video element
function onRemoteStreamAdded(event) {
console.log("Added remote stream");
remotevid.src = window.URL.createObjectURL(event.stream);
}
// when remote removes a stream, remove it from the local video element
function onRemoteStreamRemoved(event) {
console.log("Remove remote stream");
remotevid.src = "";
}
}
</script>
</body>
</html>
And the Javascript file (server.js) for the server (with same port number as above):
// create the http server and listen on port
var server = require('http').createServer();
var app = server.listen(1337, function() {
console.log((new Date()) + " Server is listening on port 1337");
});
// create the socket server on the port
var io = require('socket.io').listen(app);
// This callback function is called every time a socket
// tries to connect to the server
io.sockets.on('connection', function(socket) {
console.log((new Date()) + ' Connection established.');
// When a user send a SDP message
// broadcast to all users in the room
socket.on('message', function(message) {
console.log((new Date()) + ' Received Message, broadcasting: ' + message);
socket.broadcast.emit('message', message);
});
// When the user hangs up
// broadcast bye signal to all users in the room
socket.on('disconnect', function() {
// close user connection
console.log((new Date()) + " Peer disconnected.");
socket.broadcast.emit('user disconnected');
});
});
I have node.js installed. Next I installed express and socket.io:
npm install express
npm install socket.io
I then run this file with node to start the server.
node server.js
Accessing the index.html from the server gives me this error
Uncaught TypeError: Object #<Object> has no method 'connect'
This was being caused by the line var socket = io.connect('localhost:1337/'); in server.js
I have searched this error and have tried putting the socket.io file on the server and linking it as <script src="/socket.io/socket.io.js"></script>, doesn't change anything.
In index.html it has to be something like:
<script src="http://192.168.100.74:8080/socket.io/socket.io.js"></script>
And
var socket = io.connect('http://' + window.location.host + ':8080/');
My app.js:
var server = require('http').createServer();
var app = server.listen(8080);
var io = require('socket.io').listen(app);
io.sockets.on('connection', function(socket) {
socket.on('message', function(message) {
socket.broadcast.emit('message', message);
});
});
Project-
|-node_modules-
|socket.io
|app.js
|index.html
Hope this helps. I'm also new in this webRT and socket stuff.

Socket.IO Websocket Send message not working with Firefox and Chrome

I have a running server with apache and Socket.IO. I'm trying to send and receive message using socket.io on my website.
This is the code of my server:
var fs = require('fs');
var hskey = fs.readFileSync('file.key');
var hscert = fs.readFileSync('file.crt');
var options = {
key: hskey,
cert: hscert
};
var app = require('https').createServer(options);
var io = require('/usr/local/lib/node_modules/socket.io').listen(app);
app.listen(8181);
io.sockets.on('connection', function (socket) {
socket.emit('serverMessage', 'Bienvenue master!');
socket.broadcast.emit('serverMessage', 'New user online');
});
And this is the webpage:
<!doctype html>
<html>
<head>
<title>Socket.io Test</title>
<script src="./socket.io.js"></script>
</head>
<body>
<script>
var socket;
var firstconnect = true;
function connect() {
if(firstconnect) {
socket = io.connect('https://secure.mysite.com:8181');
socket.on('serverMessage', function(data){ message(data); });
socket.on('connect', function(){ status_update("Connected to Server"); });
socket.on('disconnect', function(){ status_update("Disconnected from Server"); });
socket.on('reconnect', function(){ status_update("Reconnected to Server"); });
socket.on('reconnecting', function( nextRetry ){ status_update("Reconnecting in "
+ nextRetry + " seconds"); });
socket.on('reconnect_failed', function(){ message("Reconnect Failed"); });
firstconnect = false;
}
else {
socket.socket.reconnect();
}
}
function disconnect() {
socket.disconnect();
}
function message(data) {
document.getElementById('message').innerHTML += "<br>" + "Server says: " + data;
}
function status_update(txt){
document.getElementById('status').innerHTML = txt;
}
function esc(msg){
return msg.replace(/</g, '<').replace(/>/g, '>');
}
function send() {
socket.send('clientMessage', 'world');
};
</script>
<h1>Socket.io Test</h1>
<div><p id="status">Waiting for input</p></div>
<div><p id="message"></p></div>
<button id="connect" onClick='connect()'/>Connect</button>
<button id="disconnect" onClick='disconnect()'>Disconnect</button>
<button id="send" onClick='send()'/>Send Message</button>
</body>
</html>
Everything seems to work fine under Safari (websocket) and Opera (json pooling) but with Firefox and Chrome (websocket) I cannot send any message from the client to the server. Everything else is working, I can handshake, connect and gets server messages. I made allot of research but seems like I'm the only one with this problem.
Thanks for helping me!
I found the problem, I was using a different version of socket.io.js then the server side.
when you attach the socket.io module to express it intercepts the socket.io route.
So when you request "https://secure.mysite.com:8181/socket.io" it will respond with
"Welcome to socket.io."
So when you request the client side socket.io.js it comes directly from the socket.io module.
"https://secure.mysite.com:8181/socket.io/socket.io.js"
So If you wan't to mod the client side library you could create a modified copy and let express serve up the file, but as you update socketio through npm you'll have to bump up your modified copy as well manually.
if in FireFox you get this error - first check enabled or no proxy. and turnoff proxy if enabled.

Client side tcp with node.js/socket.io?

I'm new to node.js/socket.io so I don't really know what I'm doing, but I've got this for my server side:
var app = require('net')
, fs = require('fs')
var server = app.createServer(function (socket) {
socket.write("Echo server\r\n");
socket.pipe(socket);
socket.on('data', function(data) {
console.log(data);
});
});
var io = require('socket.io').listen(server)
server.listen(81);
So the tcp server works when I use nc localhost 81 and send it data. However, I don't know how to connect and send data to the tcp server on a website from the server side using script tags. So what would the client side be to connect to this tcp server and send data to it?
Thanks!
Newly added code:
Server:
var app = require('net')
, fs = require('fs')
var sockets_list = [];
var server = app.createServer(function (socket) {
sockets_list.push(socket);
socket.write("Echo server\r\n");
socket.on('data', function(data) {
console.log(data);
for (var i = 0; i < sockets_list.length; i++) {
sockets_list[i].write(data);
}
});
socket.on('end', function() {
var i = sockets_list.indexOf(socket);
sockets_list.splice(i, 1);
});
});
server.listen(81);
Client:
<script type="text/javascript" src="http://localhost:82/socket.io/socket.io.js"> </script>
<script>
var socket = io.connect('http://localhost:81');
socket.on('connect', function () {
socket.send('hi');
});
socket.send('hi1');
socket.emit('hi2');
alert('here');
</script>
What happened:
I have a webpage loading which takes one socket and a nc localhost 81 which takes up another socket. So the nc displays everything the web page sends. After I connect the webpage, the alert('here'); is executed and the nc shows the http request, however, nothing else is sent to the tcp server, and the webpage is in constant refresh status. Why does the webpage never fully load, the 'hi' messages never get sent, and what about the http request to a tcp server? Why doesn't my tcp client fail with my tcp server?
Socket.io's how to use page shows you exactly how to do that.
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost/');
socket.on('connect', function () {
socket.send('hi');
socket.on('message', function (msg) {
// my msg
});
});
</script>