How to separate input/output from pipe socket server in nodejs? - javascript

I have below source code about socket server/client in nodejs.
const net = require('net');
net.createServer((socket)=>{
socket.pipe(socket);
socket.on('data', (data)=>{
console.log('receive data ', data.toString());
socket.write('this is server')
});
}).listen(3000);
console.log("Chat server running at port 5000\n");
let client = new net.Socket();
client.setEncoding('utf8');
client.connect(3000, '127.0.0.1', function() {
console.log('Connected');
client.write('Hello, server! Love, Client.');
});
client.on('data', function(data) {
console.log('Received: ' + data);
});
when I run above code, the server will send the data(which is from the client) back to the client. I know this is cased by socket.pipe(socket);. I want to keep that code and am looking for a way to separate the input/output data in client side like below:
client.on('data', function(data) {
if( the data is sent from client ){
...
} else {
//this is the data generated from server
}
});
Does anyone know how to do that in nodejs client side?

Actually you can separate out the data from client and server, depending upon what messages you emit or what you listen, from that you can distinguish between client and server.
The message you emit from server are the message, you received on the client side if client is listening to that messages, the message you emit by client are the message received on server if server is listening to the messages.
Below is the code for a socket.io
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
res.send('<h1>SocketChat Server</h1>');
});
http.listen(3000, function(){
console.log('Listening on *:3000');
});
io.on('connection', function(clientSocket){
/* Here server is listening to client 'connectUser' message so here data is sent from client*/
clientSocket.on('connectUser', function(clientNickname, groupName) {
var message = "User " + clientNickname + " was connected." + clientSocket;
console.log(message);
clientSocket.emit('userConnected');
});
});
/* Here server is emitting message('userConnected') that will be received by client. */
From above you can see that how to distinguish the client and server messages.

Related

How to make this websocket real time?

I'm integrating websockets with express on the backend and using browser's native websocket api on the client side. I have so far been able to send and receive message from the client to server and server back to client. But all this happens with a page refresh only. Isn't websocket supposed to be real time? Lets say I make a change in the message on server file, then it has to immediately reflect in my browser's console. and lets say I make a change in the message in the script file on the client side, then it has to immediately show the changes on server's console.(Also I'm using nodemon to run the server so changes has to reflect pretty quickly). But right now, I see myself making a request to / via page refresh and then server upgrading and then responding back with the message.
Please tell me if I'm missing something in the code or otherwise in the concept?
app.js
const express = require('express')
const app = express()
const path = require('path')
const WebSocketServer = require('websocket').server;
app.set('view engine', 'html');
app.use(express.static(path.join(__dirname, '/public')))
const port = 8080
app.get('/', (req, res) => {
res.render('index')
})
const server = app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
})
wsServer = new WebSocketServer({
httpServer: server
});
function originIsAllowed(origin) {
return true;
}
wsServer.on('request', function(request) {
if (!originIsAllowed(request.origin)) {
request.reject();
console.log((new Date()) + ' Connection from origin ' + request.origin + ' rejected.');
return;
}
var connection = request.accept(null, request.origin);
console.log((new Date()) + ' Connection accepted.');
connection.on('message', function(message) {
if (message.type === 'utf8') {
console.log('Received Message: ' + message.utf8Data);
connection.sendUTF("server says hi");
}
else if (message.type === 'binary') {
console.log('Received Binary Message of ' + message.binaryData.length + ' bytes');
connection.sendBytes(message.binaryData);
}
});
connection.on('close', function(reasonCode, description) {
console.log((new Date()) + ' Peer ' + connection.remoteAddress + ' disconnected.');
});
});
client.js:
const socket = new WebSocket('ws://localhost:8080');
// Connection opened
socket.addEventListener('open', function (event) {
socket.send('Hello to Server!');
});
// Listen for messages
socket.addEventListener('message', function (event) {
console.log('Message from server ', event.data);
});
I am not sure if I understand the question, but if you want the client to send message to server, you have do it the same way as it is done in open listener:
socket.send('MESSAGE FOR SERVER') or, if server should send something to client, then just
connection.send('MESSAGE FOR CLIENT').
Realtime communication with WebSocket means, the connection is created only once and the protocol is kept opened (Unlike REST API, where the connection is created with every request.)
The message must be sent actively either from server or client, there is nothing observing some message state and updating it on the other side.

Using Websocket and http server together

I am using websocket and http server together, assigning each of them a different port, when a post request hits it sends a message to client using websocket and response of http request is send when client responds to the message.
My problem is I want to create multiple websockets but a single https server, I have tried some things but unable to do it.
Current code for creating websocket and httpserver is
const app = require('express')()
bodyParser = require('body-parser')
app.use(bodyParser.json())
const net = require('net');
var client;
var res1,currentReq;
//----------------------------------------------------------------------------
// http requests listener
//----------------------------------------------------------------------------
app.listen(8001, () => console.log('Http server listening on port 8001'));
//----------------------------------------------------------------------------
// http requests handling
//----------------------------------------------------------------------------
app.post('/getUser', (req, res) => {
console.log(req.body)
res1 = res;
currentReq='getUser';
client.write('{"route":"/","data":{"username":"' + req.body.username +'"}, "res": "' + res + '"}');
//res.end('{"Extension":"' +' data '+ '"}');
console.log("/getUser finished");
// res.end('{"Extension":"' +' data '+ '"}');
});
//----------------------------------------------------------------------------
// Establishing tcp connection for incoming requests
//----------------------------------------------------------------------------
var server = net.createServer(function(connection) {
console.log ('client has connected successfully!');
client = connection;
client.on('data',function(data){
switch(currentReq)
{
case 'getUser' :
console.log('send get user response');
res1.end(data);
break;
}
console.log(data.toString());
//res1.end(data);
});
connection.pipe(connection);
});
//----------------------------------------------------------------------------
// listener for tcp connections
//----------------------------------------------------------------------------
server.listen(8000, function() {
console.log('server for localhost is listening on port 8000');
console.log('server bound address is: ' + server.address ());
});

Socket.io client cant connect to server

I have issue related to Socket.io connection to server.
Its working fine on my local, but on dev-server it cant connect.
My backend code look like this:
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
var redis = require('redis');
server.listen(8080);
console.log('CONNECTED');
io.on('connection', function (socket) {
var handshake = socket.handshake;
console.log(handshake);
console.log("new client connected");
var redisClient = redis.createClient();
redisClient.subscribe('notification');
redisClient.subscribe('rate');
redisClient.on("message", function(channel, message) {
console.log("New message: " + message + ". In channel: " + channel);
socket.emit(channel, message);
});
socket.on('disconnect', function() {
redisClient.quit();
});
});
And my client part like this:
var socket = io.connect('http://localhost:8080');
socket.on('notification', function (data) { console.log(data) }
The error that im facing is when socket.io client tries to send to URL "http://localhost:8080/socket.io/?EIO=3&transport=polling&t=MD_W4lE" request and its failing, with error ERR_CONNECTION_REFUSED. The node server is runing i tested and also tried to change localhost to 127.0.0.1 and ipv4 address, i didnt helped.

How do I properly emit data to server from client using Node.js?

When the client connects to the server a message is supposed to be emitted to the console. I'm not getting any errors so I'm confused as to what my problem actually is.
Server: As you can see the client connects.
Client: The message doesn't appear in the console.
(Forgive me for the links, I don't have 10 reputation)
How do I get the message to print to the console?
I've read other posts like this one, but they weren't helpful :(
When you do io.connect(), that call is asynchronous and not immediate. You cannot immediately emit to the server until the client generates the connect event:
var socket = io.connect()
socket.on('connect', function() {
// it is safe to call `.emit()` here
socket.emit("sndMsg", someData);
});
index.html
<html>
<head>
<script src='/socket.io/socket.io.js'></script>
<script>
var socket = io();
socket.on('welcome', function(data) {
addMessage(data.message);
// Respond with a message including this clients' id sent from the server
socket.emit('i am client', {data: 'foo!', id: data.id});
});
socket.on('time', function(data) {
addMessage(data.time);
});
socket.on('error', console.error.bind(console));
socket.on('message', console.log.bind(console));
function addMessage(message) {
var text = document.createTextNode(message),
el = document.createElement('li'),
messages = document.getElementById('messages');
el.appendChild(text);
messages.appendChild(el);
}
</script>
</head>
<body>
<ul id='messages'></ul>
</body>
</html>
server.js
var http = require('http'),
fs = require('fs'),
// NEVER use a Sync function except at start-up!
index = fs.readFileSync(__dirname + '/index.html');
// Send index.html to all requests
var app = http.createServer(function(req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.end(index);
});
// Socket.io server listens to our app
var io = require('socket.io').listen(app);
// Send current time to all connected clients
function sendTime() {
io.emit('time', { time: new Date().toJSON() });
}
// Send current time every 10 secs
setInterval(sendTime, 10000);
// Emit welcome message on connection
io.on('connection', function(socket) {
// Use socket to communicate with this particular client only, sending it it's own id
socket.emit('welcome', { message: 'Welcome!', id: socket.id });
socket.on('i am client', console.log);
});
app.listen(3000);

Connecting to a test websocket server works, but connecting to my Node.js server fails

I'm using the code below to test websockets on my browser:
this.webSocket = new WebSocket("ws://echo.websocket.org");
this.webSocket.onopen = function(evt) {
cc.log("Send Text WS was opened.");
};
this.webSocket.onmessage = function(evt) {
this.socketSendTextTimes++;
var textStr = "response text msg: " + evt.data + this.socketSendTextTimes;
cc.log(textStr);
};
The code works well, but if I connect to my own server running the code below:
var http = require('http');
var io = require('socket.io');
var server = http.createServer(function(req, res) {
// Send HTML headers and message
res.writeHead(200,{ 'Content-Type': 'text/html' });
res.end('<h1>Hello!</h1>');
});
var socket = io.listen(server);
socket.set('destroy upgrade', false);
socket.on('connection', function(client) {
client.on('message', function(event) {
console.log('Received message from client!', event);
});
client.on('disconnect', function() {
console.log('Server has disconnected');
});
});
server.listen(8080);
console.log('start to listen');
My browser displays:
hello!
But the listening socket does not do anything. How can I connect to the Socket.IO server using websockets?
Socket.IO uses alternate transport methods than the native websocket, even when emulating websockets themselves. You will need the client library to connect to Socket.IO sockets.

Categories

Resources