I'm fairly new to node js and I need to solve a problem. I have two tcp servers that can send out messages. I need a component between them (a client?): when the first server sends out a message, this middle component must take it (because I need to parse that) and send it to the second server and viceversa (from second server to first server). How to do this in node? Thank you!
a basic tcp
server, but for some reason omit a client connecting to it.
In your middleware, you'll have to have a client that gets the message and forward it to the other server.
At the server
var net = require('net');
var server = net.createServer(function(socket) {
socket.write('Echo server\r\n');
socket.pipe(socket);
});
server.listen(1337, '127.0.0.1');
At the client
var net = require('net');
var client = new net.Socket();
client.connect(1337, '127.0.0.1', function() {
console.log('Connected');
client.write('Hello, server! Love, Client.');
});
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');
});
Related
I want to know how to create a server in Nodejs to connect clients without the need of a browser. It is difficult to explain, but I mean if it is possible to create a server and also create a client application to connect directly between computers. Attention, I do not want to create an http server.
Maybe next sample that's you are looking for. I think you need use tcp instead http.
/*
TCP (net) Server
*/
var net = require('net');
var server = net.createServer(function(socket) {
socket.write('Echo server\r\n');
socket.pipe(socket);
});
server.listen(1337, '127.0.0.1');
/*
$ netcat 127.0.0.1 1337
You should see:
> Echo server
*/
/* TCP (net) client */
var net = require('net');
var client = new net.Socket();
client.connect(1337, '127.0.0.1', function() {
console.log('Connected');
client.write('Hello, server!');
});
client.on('data', function(data) {
console.log('Received: ' + data);
client.end(); // kill client after server's response
});
client.on('close', function() {
console.log('Connection closed');
});
I have a socket server in node. When it revives a new message, it writes it to the socket. But from which it has revived, writes to the corresponding socket, not all connections.
Server.js
var server = net.createServer(function(sock){
console.log('new client connected');
sock.on('data', function(data) {
console.log('Server received');
// ** NOT sending to all clients **
sock.write('broadcasting to others...');
});
});
Client.js
var client = new net.Socket();
client.connect(PORT, HOST, function() {
console.log('Client connected to: ' + HOST + ':' + PORT);
// 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('Client is connected!!');
});
client.on('data', function(data) {
console.log('Client received: ' + data);
});
How can I broadcast one client message to all other clients?
Following up on my suggestion to use a Set to keep track of all the connected sockets, this is one way to implement that. This implementation maintains that Set as connections come and go by listening to both the connect event and the end event.
This implementation also supports a desirable feature to send to all connected sockets EXCEPT the one that triggered the event (which I think is what your situation would want):
// Set of all currently connected sockets
const connectedSockets = new Set();
// broadcast to all connected sockets except one
connectedSockets.broadcast = function(data, except) {
for (let sock of this) {
if (sock !== except) {
sock.write(data);
}
}
}
const server = net.createServer(function(sock){
console.log('new client connected');
connectedSockets.add(sock);
sock.on('end', function() {
connectedSockets.delete(sock);
});
sock.on('data', function(data) {
console.log('Server received');
connectedSockets.broadcast(data, sock);
});
});
I believe you can always keep the socket reference for each client in an array when they established connection to the server. To broadcast, simply loop the array and use perform the write()
var clients = [];
var server = net.createServer(function(sock){
console.log('new client connected');
clients.push(sock);
sock.on('data', function(data) {
console.log('Server received');
for(var i = 0; i < clients.length; i++) clients[i].write('broadcasting..');
});
});
Or if you have the control on both server and client, I think it is better to use websocket or socket.io as it offer broadcast feature.
I am trying to connect to a socket.io-client using the following code:
Server:
// Load requirements
var http = require('http'),
io = require('socket.io');
// Create server & socket
var server = http.createServer(function(req, res){
// Send HTML headers and message
res.writeHead(404, {'Content-Type': 'text/html'});
res.end('<h1>Aw, snap! 404</h1>');
});
server.listen(8080);
io = io.listen(server);
// Add a connect listener
io.sockets.on('connection', function(socket) {
console.log('Client connected.');
// Disconnect listener
socket.on('disconnect', function() {
console.log('Client disconnected.');
});
});
Client:
console.log('1');
// Connect to server
var io = require('socket.io-client')
var socket = io.connect('localhost:8080', {reconnect: true});
console.log('2');
// Add a connect listener
socket.on('connect', function(socket) {
console.log('Connected!');
});
console.log('3');
I don't get the Connected console log or Client Connected console log and I don't know why! The code sample is taken from another question posted: Link and I don't see any solution to the problem...
Use the same version of socket io client and server. It will work perfectly.
Also you need to add protocol with path.
change
var socket = io.connect('localhost:8080', {reconnect: true});
to
var socket = io.connect('http://localhost:8080', {reconnect: true});
Assuming you are using a socket.io version greater than 1.0, on the server, change this:
// Add a connect listener
io.sockets.on('connection', function(socket) {
console.log('Client connected.');
// Disconnect listener
socket.on('disconnect', function() {
console.log('Client disconnected.');
});
});
to this:
// Add a connect listener
io.on('connection', function(socket) {
console.log('Client connected.');
// Disconnect listener
socket.on('disconnect', function() {
console.log('Client disconnected.');
});
});
See the socket.io documentation reference here.
You don't want to be listening for this event only on already connected sockets. You want to listen for this event on any socket, even a newly created one.
Also, be very careful when reading socket.io code in random places on the internet. Some things changed significantly from v0.9 to v1.0 (I don't know if this was one of those things or not). You should generally always start with the socket.io documentation site first since that will always represent the latest version. Then, if looking at other internet references, make sure you only use articles that are later than mid-2014. If you don't know the vintage of an article, it's best not to rely on it without corroboration from a more recent article.
you can use localhost. It works for me as well. You must use your ip address and port that works for you
Is it possible to connect to a NodeJS Server from another server? Two NodeJS servers communicating with each other?
//Server Code
var io = require('socket.io').listen(8090);
io.sockets.on('connection', function (socket) {
io.sockets.emit('this', { will: 'be received by everyone'});
socket.on('private message', function (from, msg) {
console.log('I received a private message by ', from, ' saying ', msg);
});
socket.on('disconnect', function () {
io.sockets.emit('user disconnected');
});
});
//Client Code in Server Code. Connecting to another server.
io.connect( "http://192.168.0.104:8091" ); //Connect to another server from this one.
//ETC...
Here's a simple example that creates a server and a client that connects to that server. Remember that what you send has to be a buffer (strings are automatically converted to buffers). The client and server works independently of eachother, so can be put in the same app or on totally different computers.
Server (server.js):
const net = require("net");
// Create a simple server
var server = net.createServer(function (conn) {
console.log("Server: Client connected");
// If connection is closed
conn.on("end", function() {
console.log('Server: Client disconnected');
// Close the server
server.close();
// End the process
process.exit(0);
});
// Handle data from client
conn.on("data", function(data) {
data = JSON.parse(data);
console.log("Response from client: %s", data.response);
});
// Let's response with a hello message
conn.write(
JSON.stringify(
{ response: "Hey there client!" }
)
);
});
// Listen for connections
server.listen(61337, "localhost", function () {
console.log("Server: Listening");
});
Client (client.js):
const net = require("net");
// Create a socket (client) that connects to the server
var socket = new net.Socket();
socket.connect(61337, "localhost", function () {
console.log("Client: Connected to server");
});
// Let's handle the data we get from the server
socket.on("data", function (data) {
data = JSON.parse(data);
console.log("Response from server: %s", data.response);
// Respond back
socket.write(JSON.stringify({ response: "Hey there server!" }));
// Close the connection
socket.end();
});
The conn and socket objects both implement the Stream interface.
Check Substrack's dnode. It auto maps literal objects from the 1st env to the 2nd one. You gain a kind of RPC out of the box. And it works in the browser too...
Here's my problem:
I have server A, running node.js and using socket.io for communicating with clients (web browsers). This all is running fine and dandy.
However, now that I have server B, which also needs to connect to server A through websockets, I have hit a wall. None of the node.js websocket clients I've found won't work with the socket.io on the server A.
So, this is the case I'm striving for:
.--------. .----------. .----------.
| CLIENT | <--> | SERVER A | <--> | SERVER B |
'--------' '----------' '----------'
Client-server A connection is done through socket.io
Now, Server B (running node.js) should connect to server A via websocket (in order to go through port 80). But...
Even the example code in socket.io-client module doesn't work... :/
// Connect to server
var socket = new io.Socket('localhost', {port: 8080});
socket.connect();
// Add a connect listener
socket.on('connect', function(socket) {
console.log('Connected.');
});
The code just passes without any errors and execution ends after few seconds.
Update: Code samples
Server (which works just fine) looks like this:
// Load requirements
var http = require('http'),
io = require('socket.io');
// Create server & socket
var server = http.createServer(function(req, res){
// Send HTML headers and message
res.writeHead(404, {'Content-Type': 'text/html'});
res.end('<h1>Aw, snap! 404</h1>');
});
server.listen(8080);
io = io.listen(server);
// Add a connect listener
io.sockets.on('connection', function(socket) {
console.log('Client connected.');
// Disconnect listener
socket.on('disconnect', function() {
console.log('Client disconnected.');
});
});
Client looks like this
console.log('1');
// Connect to server
var io = require('socket.io-client')
var socket = new io.Socket('localhost', {port: 8080});
socket.connect();
console.log('2');
// Add a connect listener
socket.on('connect', function(socket) {
console.log('Connected!');
});
console.log('3');
1, 2 and 3 prints out just fine, no errors, and few seconds later the process just exits
Also, server A doesn't output anything to the log, even though I have the socket.io logging set on "everything".
For future people:
Here is 2 very simple Node.js apps that use socket.io to connect, send and receive messages between each other.
Required package is:
npm install socket.io
Node-App-1 server.js:
var io = require('socket.io').listen(3000);
io.on('connection', function (socket) {
console.log('connected:', socket.client.id);
socket.on('serverEvent', function (data) {
console.log('new message from client:', data);
});
setInterval(function () {
socket.emit('clientEvent', Math.random());
console.log('message sent to the clients');
}, 3000);
});
Node-App-2 client.js:
var io = require('socket.io-client');
var socket = io.connect("http://localhost:3000/", {
reconnection: true
});
socket.on('connect', function () {
console.log('connected to localhost:3000');
socket.on('clientEvent', function (data) {
console.log('message from the server:', data);
socket.emit('serverEvent', "thanks server! for sending '" + data + "'");
});
});
Turns out I was using old examples, for some reason, even though I triple checked them. Well, doh.
Also, it turned out that the socket.io-client is broken on latest Node (6.x.x). Managed to find an update from github for it, replaced the files and yay, everything's working!
Edit: Unfortunately I didn't save any links to working examples but after quickly skimming through the code it seems that the only changes were to the client code, which now looks like this:
console.log('1');
// Connect to server
var io = require('socket.io-client')
var socket = io.connect('localhost:8080', {reconnect: true});
console.log('2');
// Add a connect listener
socket.on('connect', function(socket) {
console.log('Connected!');
});
console.log('3');
Here is a snippet of code I wrote, it's using socket.io 1.0.6 and socket.io-client 1.0.6. The case is the following:
Server A (Socket.io Client) <---> Server B (Socket.io Server)
Server B (Server):
// Load requirements
var http = require('http'),
io = require('socket.io');
// Create server & socket
var server = http.createServer(function(req, res)
{
// Send HTML headers and message
res.writeHead(404, {'Content-Type': 'text/html'});
res.end('<h1>Aw, snap! 404</h1>');
});
server.listen(8080);
io = io.listen(server);
// Add a connect listener
io.sockets.on('connection', function(socket)
{
console.log('Client connected.');
// Disconnect listener
socket.on('disconnect', function() {
console.log('Client disconnected.');
});
});
Server A (Client):
console.log('1');
// Connect to server
var io = require('socket.io-client');
var socket = io.connect('http://localhost:8080', {reconnect: true});
console.log('2');
// Add a connect listener
socket.on('connect', function(socket) {
console.log('Connected!');
});
console.log('3');
If I'm using localhost:8080 only on the client server it doesn't connect.