I'm trying to create something like chat using nodejs. I'm a newbie in nodejs and i want to create it without socket.io (i want to learn how it works). Here is the code i'm using.
var http = require('http');
var net = require('net');
var server = http.createServer(function(req,res){
res.writeHead(200,{'content-type' : 'text/html'});
res.write('<a href="./lol/">lol</a><br>');
res.end('hello world: '+req.url);
var client = new net.Socket();
client.connect('7001', '127.0.0.1', function() {
console.log('CONNECTED TO: ');
// Write a message to the socket as soon as the client is connected, the server will receive it as message from the client
client.write('I am Chuck Norris!');
});
// Add a 'data' event handler for the client socket
// data is what the server sent to this socket
client.on('data', function(data) {
console.log('DATA: ' + data);
// Close the client socket completely
client.destroy();
});
// Add a 'close' event handler for the client socket
client.on('close', function() {
console.log('Connection closed');
});
//req.
});
server.listen(7000);
require('net').createServer(function (socket) {
console.log("connected");
socket.on('data', function (data) {
console.log(data.toString());
});
}).listen(7001);
And all works fine, (i think). When i open localhost:7000 i'm getting in node CMD messages about "CONNECTED TO:" and "connected" and "I am Chack Norris". After that i'm trying to write in the browser console:
var conn = new WebSocket('ws://localhost:7001/');
Also no errors, but when i try this line:
conn.send('lol');
I'm getting an error: "Uncaught DOMException: Failed to execute 'send' on 'WebSocket': Still in CONNECTING state.(…)"
And after some time i get one more error: "WebSocket connection to 'ws://localhost:7001/' failed: WebSocket opening handshake timed out"
maybe this code is wrong, but i have tried everything that i found through google. Can someone help me with this?