flutter socket time out to connecting the remote server but it is connected local host perfectly #server side node js - node.js

I want to make the socket to be connected to the node.js socket but it is unable because time out error . but it is connected local host perfectly.
initSocket() {
socket = IO.io('http://206.244.230.30', <String, dynamic>{ 'autoConnect': true,
'transports': ['websocket'], });
socket!.connect();
socket!.onConnect((_) { print('Connection established'); }); socket!.onDisconnect((_) => print('Connection Disconnection')); socket!.onConnectError((err) => print(err)); socket!.onError((err) => print(err));
''' node js server side'''
const server = require('http').createServer()
const io = require('socket.io')(server)
io.on('connection', function (client) {
console.log('client connect...', client.id);
client.on('typing', function name(data) {
console.log(data);
io.emit('typing', data)
})
client.on('message', function name(data) {
console.log(data);
io.emit('message', data)
})
client.on('location', function name(data) {
console.log(data);
io.emit('location', data);
})
client.on('connect', function () {
})
client.on('disconnect', function () {
console.log('client disconnect...', client.id)
// handleDisconnect()
})
client.on('error', function (err) {
console.log('received error from client:', client.id)
console.log(err)
})
})
var server_port = process.env.PORT || 3000;
server.listen(server_port, function (err) {
if (err) throw err
console.log('Listening on port %d', server_port);
});
''' I want to make the socket to be connected to the node.js socket but it is unable because time out error . but it is connected local host perfectly.'''

Related

How to send multiple data streams from single client to a tcp server

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);
});

Nodejs , Redis,Sockets

I have a nodejs app which reads data from redis and I am unable to push it into socket. In the c.write(message) part, if I hardcode(example c.write('hello') ,the messages are being put to the socket but when i put it as c.write(message), nothing is going to the socket. Thanks in advance,
var net = require('net');
var split = require('split');
var Redis = require('ioredis');
var redis = new Redis();
var server = net.createServer(function(c) {
console.log('client connected');
c.on('end', () => {
console.log('client disconnected');
});
redis.subscribe('test-channel');
redis.on('message', function(channel, message) {
console.log(message);
c.write(message);
c.pipe(c);
});
});
server.on('error', (err) => {
throw err;
});
server.listen(3005, 'localhost', () => {
console.log('server bound');
});
I have got the answer.
Just add below lines to your code :
var message_redis = message+'\r'+'\n';
c.write(message_redis);

function not called by nodejs ws-express on connection handler

I've implemented a websockets api on top of a swagger-express node server.
For websockets I'm using express-ws which utilises the excellent ws library.
However I have come across a problem where the function setInterval is not being called when a websocket client connects.
Confusingly though in the ws.on('connection' function the console.log('websocket connected'); does execute while the setInterval function does not.
Can someone please point out what is wrong with my code?
'use strict';
var SwaggerExpress = require('swagger-express-mw');
var app = require('express')();
module.exports = app; // for testing
var expressWs = require('express-ws')(app);
var IndexWS = require('./api/controllers/indexWS');
var config = {
appRoot: __dirname // required config
};
app.ws('/', function(ws, req) {
ws.on('connection', function(conn) {
console.log('websocket connected');
setInterval(function timeout() {
console.log('conn');
}, 500);
});
ws.on('close', function() {
console.log('The connection was closed!');
});
ws.on('error', function() {
console.log('websocket error!');
});
ws.on('message', function(msg) {
setTimeout(function timeout() {
ws.send("500 delay");
}, 500);
});
console.log('websocket connected');
});
SwaggerExpress.create(config, function(err, swaggerExpress) {
if (err) { throw err; }
// install middleware
swaggerExpress.register(app);
var port = process.env.PORT || 3030;
app.listen(port, '0.0.0.0');
if (swaggerExpress.runner.swagger.paths['/hello']) {
console.log('server running on port ' + port );
}
});

nodejs client server issue when reconnecting

I am very new to nodejs and I have some client-server implementation, which basically works the following manner : I submit a form which throws data to a client remote server. The latter send me back some new data.
net.createServer(function (socket) {
socket.on('error',function(err){ console.error(err)});
socket.on('data', function (data) {
some_method(data)
});
socket.on('end', function() {
console.log('CONN: disconnected');
//socket.end();
});
app.post('/api/sender', function(req, res) {
socket.write(some_input);
res.end();
});
}).listen(9000);
This works well until the client disconnects itself and reconnects, then I get the following error message :
{ [Error: This socket has been ended by the other party] code: 'EPIPE' }
And the code crashes at this line socket.write(some_input). Can someone can help ?
here's how this could be tackled :
module.exports = function(app) {
var clients = {};
var server = net.createServer(function (socket) {
server.getConnections(function(err, count) {
var id = sha1(socket.remoteAddress);
clients[id] = {
stream: through(),
socket: socket,
}
clients[id].stream.pipe(socket);
});
socket.on('error',function(err){ console.error(err)});
socket.on('data', function (data) {
some_method(data)
});
socket.on('end', function() {
console.log('CONN: disconnected');
socket.end();
});
app.post('/api/sender', function(req, res) {
// here id is the IP adress got from req
if (clients[id]) {
clients[id].stream.write(input);
}
res.end();
});
}).listen(9000);
};

Node.js socket.io server callback not working

I'm working on a simple Node.js bi-directional client\server communication channel and I'm attempting to use socket.io on the server and socket.io-client on the client.
I've inserted the code below, as you'll see it's pretty basic stuff, and I'm running both on my local machine - to minimise complexity.
The behaviour I'm seeing is:
I start the server.
The server logs 'Server started' to the console.
I start the client.
The client logs 'Server is ready!'
Nothing else happens...
What I'd expect is the server to log a 'Client is ready!' message and then the content ('Ready received').
I've even used WireShark to sniff the line and it does appear that the client is emitting the message, as designed - but the callback on the server isn't firing.
I'm running node v0.8.4 with express v3.1.0, socket.io v0.9.13 and socket.io-client v0.9.11 (all installed via npm).
Here's the server code...
var http = require('http'),
express = require('express'),
app = express(),
server = http.createServer(app);
app.configure(function(){
app.use(express.static(__dirname + '/public'));
});
server.listen(8080);
console.log("Server started");
var io = require('socket.io').listen(server);
io.sockets
.on('connection', function(socket){
socket.emit('server ready', { msg: 'ready' }) ;
})
.on('comms', function(content) {
console.log('Client is ready!');
console.log(content);
});
And here's the client code...
var clientio = require('socket.io-client');
var socket = new clientio.connect('http://localhost', { port: 8080 });
socket
.on('server ready', function(data){
console.log('Server is ready!');
socket.emit('comms', 'Ready received');
})
.on('connect-error', function(error) {
console.log('Connection Error\n' + error);
})
.on('error', function(error) {
console.log('Socket Error\n' + error);
})
The documentation and examples for both socket.io and socket.io-client are somewhat confused (to be charitable) and they appear to be a bit of a moving target... but from what I can tell, I think this should work.
I'm hoping someone can give me advice as to where I'm going wrong?
In your server you have this code:
io.sockets
.on('connection', function(socket){
socket.emit('server ready', { msg: 'ready' }) ;
})
.on('comms', function(content) {
console.log('Client is ready!');
console.log(content);
});
What you should do is something like this:
io.sockets.on('connection', function(socket){
socket.emit('server ready', { msg: 'ready' });
socket.on('comm', function(content){
console.log('Client is ready!');
console.log(content);
});
});
hopefully this is doing more or less what you need it to do. Just a couple of minor changes.
app.js
var app = require('express')()
, server = require('http').createServer(app)
, io = require('socket.io').listen(server);
// using 'connect' to handle static pages
app.use(require('connect').static(__dirname + '/public'))
server.listen(8080);
app.get('/', function (req, res) {
res.sendfile(__dirname + '/index.html');
});
io.sockets.on('connection', function (socket) {
socket.emit('server ready', { msg: 'ready' });
socket.on('comms', function(content) {
console.log(('Client is ready\n'));
console.log(content);
});
});
index.html
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">
</script>
<script>
window.jQuery || document.write('<script src="js/jquery-1.8.3.min.js"><\/script>')
</script>
<script src="/socket.io/socket.io.js"></script>
</head>
<body>
<script>
(function (d, b) {
function bindEvents() {
function doSomething(msg) {
$.each(msg, function (key, value) {
console.log('doSomething...');
$("body").append("<p>" + value + "</p>")
});
};
// var socket = io.connect();
var socket = io.connect('http://localhost');
socket.on('server ready', function (msg) {
console.log('Server is ready!\n', msg);
doSomething(msg);
socket.emit('comms', {
msg: 'Client is Ready'
});
});
socket.on('connect-error', function (err) {
console.log('Connection Error\n', err);
});
socket.on('error', function (err) {
console.log('Connection Error\n', err);
});
};
$(document).ready(function () {
bindEvents()
});
})(jQuery, this)
</script>

Resources