I wanna create socket server like a Socket.io because socket.io can't work with Corona SDK. So I need custom socket server. I create socket server with using net module and it is work good. But I need using http module because I write REST API. I try create sample socket server from http module but have errors.
var net = require('net');
var HOST = 'localhost';
var PORT = 9999;
var server = require('http').createServer(function(request, response) {
response.end('Hello from server');
});
server.on('connection', function(socket) {
socket.on('data', function(data) {
data = data.toString('utf-8');
console.log(data);
socket.write('Hello from server');
});
socket.on('error', function(error) {
console.log(error);
});
});
server.listen(PORT, HOST);
var client = new net.Socket();
client.connect(PORT, HOST, function() {
console.log('CONNECTED TO: ' + HOST + ':' + PORT);
client.write('I am Chuck Norris!');
});
client.on('data', function(data) {
console.log('DATA: ' + data);
client.destroy();
});
client.on('close', function() {
console.log('Connection closed');
});
If I run this script I got error:
CONNECTED TO: localhost:9999
I am Chuck Norris!
Error: This socket is closed
at Socket._writeGeneric (net.js:692:19)
at Socket._write (net.js:743:8)
at doWrite (_stream_writable.js:329:12)
at writeOrBuffer (_stream_writable.js:315:5)
at Socket.Writable.write (_stream_writable.js:241:11)
at Socket.write (net.js:670:40)
at Socket.<anonymous> (/var/work/projects/edorium/Server/test/test.js:49:16)
at emitOne (events.js:101:20)
at Socket.emit (events.js:191:7)
at readableAddChunk (_stream_readable.js:178:18)
{ Error: Parse Error
at socketOnData (_http_server.js:411:20)
at emitOne (events.js:101:20)
at Socket.emit (events.js:191:7)
at readableAddChunk (_stream_readable.js:178:18)
at Socket.Readable.push (_stream_readable.js:136:10)
at TCP.onread (net.js:560:20) bytesParsed: 0, code: 'HPE_INVALID_METHOD' }
Connection closed
Why this happed and how fix this?
Additional to answer
I add HTTP headers to request and all works good!
Code sample below:
var http = require('http');
var net = require('net');
var express = require('express');
var HOST = 'localhost';
var PORT = 9999;
var app = express();
var server = http.Server(app);
app.get('/', function (req, res) {
res.send('Hello World!fff');
});
server.listen(PORT, HOST);
server.on('connection', function(socket) {
socket.on('data', function(data) {
data = data.toString('utf-8');
console.log(data);
socket.write('Hello from server');
});
socket.on('error', function(error) {
console.log(error);
});
socket.on('end', function() {
console.log('Socket end');
});
});
// Client
var client = new net.Socket();
client.connect(PORT, HOST, function() {
console.log('CONNECTED TO: ' + HOST + ':' + PORT);
var messagae = '' +
'GET /' +
'Host:localhost:9999' +
'Content-Type:text/plain;charset=windows-1251' +
'Content-Length:6' +
'Connection:Keep-Alive;' +
'Hello!';
client.write(messagae);
});
client.on('data', function(data) {
console.log('DATA: ' + data);
});
client.on('close', function() {
console.log('Connection closed');
});
at TCP.onread (net.js:560:20) bytesParsed: 0, code: 'HPE_INVALID_METHOD' }
Since you have explicitly created a HTTP server this server is expecting a HTTP request. But you are just sending "I am Chuck Norris!" which is definitely not a HTTP request. Therefore the server closes the connection.
To send a HTTP request you might use http.request. Alternatively you can study the HTTP standard and build a proper HTTP request yourself.
Your client was disconnect
var net = require('net');
var HOST = 'localhost';
var PORT = 9999;
var server = net.createServer(function(socket) {
socket.write('Echo server\r\n');
socket.on('data', function(data){
console.log(data);
textChunk = data.toString('utf8');
console.log(textChunk);
socket.write("================");
});
});
server.listen(PORT, '127.0.0.1');
server.listen(PORT, HOST);
var client = new net.Socket();
client.connect(PORT, HOST, function() {
console.log('CONNECTED TO: ' + HOST + ':' + PORT);
client.write('I am Chuck Norris!');
});
var i = 0;
client.on('data', function(data) {
console.log('Received: ' + data);
i++;
if(i==2)
client.destroy();
} );
client.on('close', function() {
console.log('Connection closed');
});
Related
Server Side code
var net = require('net');
var server = net.createServer((connection) => {
console.log('server connected');
connection.on('data', (data) => {
console.log('data received');
console.log('data is: \n' + data);
});
});
var HOST = '127.0.0.1';
var PORT = '8000'
server.listen(PORT, HOST, function() {
//listening
console.log('server is listening to ' + PORT + '\n');
server.on('connection', function(){
console.log('connection made...\n')
})
});
Client Side Code
var client = new net.Socket()
//connect to the server
client.connect(PORT,HOST,function() {
'Client Connected to server'
//send a file to the server
var fileStream = fs.createReadStream(__dirname + '/readMe.txt');
// console.log(__dirname + '/readMe.txt');
fileStream.on('error', function(err){
console.log(err);
})
fileStream.on('open',function() {
fileStream.pipe(client);
});
});
//handle closed
client.on('close', function() {
console.log('server closed connection')
});
client.on('error', function(err) {
console.log(err);
});
I want to know how can we achieve creating a client and a TCP server and sending multiple data from only one client to server.
I know there can be multiple clients that can connect to server that request to server and get response back but I don't want that, I want to know is it possible that a single client can send multiple data streams to a server in node.js.
The thing is suppose there is a file in which 200 lines of chunk data is present so I know we can read that file using createReadStream but suppose there are multiple files which has 200 lines of data (example) so how to send these multiple files over TCP server
Any example would be appreaciated.
Please give an explanation using a example as I am new to node.js
The example above is sending the data of one file to the server, My question what if the client want to send hundreds of files (or any data streams), So how can he send to through a single medium to TCP server ?
This is possible using the net module, the fs module, and a basic forEach construct for looping over the files:
server.js
const net = require('net');
const host = "localhost";
const port = 3000;
const server = net.createServer((connection) => {
console.log('server connected');
connection.on('data', (data) => {
console.log(`data received: ${data}`);
});
});
server.listen(port, host, function () {
console.log(`server is listening on ' + ${port}`);
server.on('connection', function () {
console.log('connection made...\n')
})
});
client.js
const net = require("net");
const fs = require("fs");
const port = 3000;
const host = "localhost";
const files = [
"file1.txt",
"file1.txt",
"file1.txt"
// As many files as you want
]
const client = new net.Socket()
client.connect(port, host, function () {
files.forEach(file => {
const fileStream = fs.createReadStream(file);
fileStream.on('error', function (err) {
console.log(err);
})
fileStream.on('open', function () {
fileStream.pipe(client);
});
});
});
client.on('close', function () {
console.log('server closed connection')
});
client.on('error', function (err) {
console.log(err);
});
I am loading my scripts using
<script src="https://cdn.socket.io/socket.io-1.4.5.js"></script>
<script src="/js/chat.js"></script>
My chat.js script is :
var socket = io();
socket.on('connect', function(){
var chatForm = document.forms.chatForm;
if (chatForm) {
var chatUsername = document.querySelector('#chat-username');
var chatMessage = document.querySelector('#chat-message');
chatForm.addEventListener("submit", function(e){
console.log("working")
//prevents page from reloading
e.preventDefault();
//emit the message with the socket
socket.emit('postMessage',{
username: chatUsername.value,
message: chatMessage.value,
});
chatMessage.value='';
chatMessage.focus();
});//chatform event
socket.on('updateMessages', function(data) {
showMessage(data);
});//update messages
}//chatForm
})
function showMessage(data) {
var chatDisplay = document.querySelector('.chat-display')
var newMessage = document.createElement('p');
newMessage.className = 'bg-success chat-text';
newMessage.innerHTML = '<strong>' + data.username + '<strong>:</strong>' +
data.message
chatDisplay.insertBefore(newMessage, chatDisplay.firstChild);
}
My app.js file uses:
app.set('port', process.env.PORT || 3000 );
var server = app.listen(app.get('port'), function() {
console.log('Listening on port ' + app.get('port'));
});
io.attach(server);
io.on('connection', function(socket) {
console.log("user connected");
socket.on('postMessage', function(data) {
io.emit('updateMessages', data);
});
});
I am getting the following errors in my console and have no idea how to fix them. Somebody please help!
The server is listening on port 3000. My console is saying that there is an unhandled 'error' event
In your app.js file, you should connect socketIO before listening:
const socketIO = require('socket-io');
const io = socketIO(app);
io.on('connection', function(socket) {
console.log("user connected");
socket.on('postMessage', function(data) {
io.emit('updateMessages', data);
});
});
app.set('port', process.env.PORT || 3000 );
app.listen(app.get('port'), function() {
console.log('Listening on port ' + app.get('port'));
});
Let try it, because I think after listening, everything won't work. We should connect socketIO before listening.
Knowing that TCP is a stream based protocol, in the following example of a client server in nodejs what is telling the server that the client has finished sending all data?
Server
var net = require('net');
var server = net.createServer(function(socket) {
var remoteAddress = socket.remoteAddress + ':' + socket.remotePort;
console.log('new client connected: %s', remoteAddress);
socket.write('Echo server');
socket.pipe(socket);
});
server.listen(1337, '127.0.0.1');
client
var client = new net.Socket();
client.connect(1337, '127.0.0.1', function() {
console.log('Connected');
for ( var i=0 ; i<100; i++) {
// console.log(i);
client.write('Hello, server! Love, Client.\r\n');
}
});
client.on('data', function(data) {
console.log('Received: ' + data);
client.destroy(); // kill client after server's response
});
client.on('close', function() {
console.log('Connection closed');
});
Thanks
I start create server with Nodejs and socket.io in simple way.
In client connect just fine but when emit pong to server it never show.
This code:
SERVER
var PORT = 3003;
var io = require('socket.io')(PORT);
var clients = [];
setInterval (function() {
io.sockets.emit('ping');
}, 3000);
io.on('connection', (function(socket) {
socket.emit ('welcome', { message: 'Connection complete', id: socket.id });
clients.push ({id: socket.id, clientSocket: socket});
print ('Client connected ' + socket.id);
socket.on('disconnect', function() {
clients.splice(clients.indexOf(socket), 1);
print (socket.id + " is disconnected.");
});
socket.on('pong', function(args) {
print (args + " is pong.");
});
}).bind(this));
print('Server starting ...');
CLIENT:
var PORT = 3003;
var io = require('socket.io-client');
var socket = io.connect('http://localhost:' + PORT);
socket.on('connect', function(){
print ('Client connected...');
});
socket.on('welcome', function(args) {
print (args.message + ' / ' + args.id);
// socket.disconnect();
});
socket.on ('ping', function(args) {
socket.emit ('pong', { id: socket.id });
print ('Receive ping...');
});
print ('Client Starting...');
Executing this code:
var fs = require('fs');
var Socket = require('net').Socket;
var socket = new Socket();
console.log('connecting to: ' + server.host + ':' + server.port );
socket.connect( server.host, server.port );
socket.on('error', function(err) {
console.log(arguments);
});
socket.on('connect', function() {
console.log('connected');
});
socket.on('end', function() {
console.log('socket ended');
});
Always throws this error:
{ '0': { [Error: connect ENOENT] code: 'ENOENT', errno: 'ENOENT', syscall: 'connect' } }
I'm on CloudLinux(x64) based shared hosting with SSH access.
You have your host and port backwards. According to the documentation, you should be doing:
socket.connect(server.port, server.host);
Server Side:-
var net = require('net');
var server = net.createServer(functi`on (socket){
socket.write("hi\n");
socket.write("you there\n");
socket.on("data", function(dd) {
console.log(data);
});
});
server.listen(8001);
Client side:-
var fs = require('fs');
var Sock = require('net');
var socket = Sock.Socket();
socket.connect(8001,"127.0.0.1", function() {
console.log('connecting to: ' + server.host + ':' + server.port );
});
socket.on('connect', function() {
console.log('connected');
});
socket.on('error', function(err) {
console.log(arguments);
});
socket.on('end', function() {
console.log('socket ended');
});