Using Socker.io, emitting does nothing just after connecting - node.js

I just started using socket.io for my Node.js server. My problem is that I cannot emit anything immediately after connecting.
Nothing happens. No errors. But no emitting !
This is server:
const app = express();
const server = app.listen(3000);
const io = socket(server);
io.on("connect", (socket: Socket) => {
console.log("Client connected...");
// This does nothing
socket.emit("Sending immediately", 'sent!');
setTimeout(() => {
socket.emit("Sending with delay", 'delayed');
}, 1000);
}
And the client code is this:
(I'm checking the received messages in Firefox Network tab)
export class Server {
private io: SocketIOClient.Socket;
constructor() {
this.io = io('127.0.0.1:3000');
}
...
}

Related

React client receives two connections using Socket.io

I am developing a simple app with SocketIO and I am encountering this problem. In the server I have the following code:
const httpServer = require('http').createServer();
const socketIO = require('socket.io');
const port = process.env.PORT_WS || 5001;
const io = socketIO(httpServer, { cors: { origin: '*' } });
io.on('connection', (socket) => {
console.log('Connected to socket');
socket.on('join-room', () => {
console.log('joined room')
});
});
httpServer.listen(port, () => {
console.log(`Listening on the port ${port}`);
});
In the client I have the following code:
import { io } from 'socket.io-client';
export default class SocketConnection {
constructor() {
this.initializeSocketConnection();
this.initializeSocketEvents();
}
initializeSocketConnection() {
console.log('I am here');
this.socket = io('ws://localhost:5001');
}
initializeSocketEvents() {
this.socket.on('connect', () => {
console.log('Socket connected');
});
}
}
I get in the console two Socket connected messages.
This is not a re-render issue because the I am here message is logged only once.
I am using socket.io version 4.0.1 both in the client and in the backend.
So this is happening because, in React Strict Mode, constructors are called two times. React seems to hide this. As the console.log('Socket connected'); is inside an "on" event, React has no way to "hide" this. Thus, 'I am here' is going to be shown once but 'Socket connected' is going to be shown twice.

Flutter Socket io disconnects after some seconds

Am using a local socket server using express which is expose to the internet using ngrok. This is the server code:
const app = require('express')();
const http = require('http').createServer(app);
app.get('/', (req, res) => {
res.send("Node Server is running. Yay!!");
});
//Socket Logic
const socketio = require('socket.io')(http)
socketio.on("connection", (userSocket) => {
console.log('Connected to socket');
});
http.listen(3000, () => {
console.log('listening on port 3000');
});
and my connection logic is:
void connectToServer() {
try {
socket = io('https://fa6387728fcd.ngrok.io', <String, dynamic>{
'transports': ['websocket'],
'autoConnect': false,
});
// Connect to websocket
socket.connect();
// Handle socket events
socket.on('connect', (data) => print('Connected to socket server'));
socket.on('disconnect', (reason) => print('disconnected $reason'));
socket.on('error', (err) => print('Error: $err'));
} catch (e) {
print(e.toString());
}
}
But i keep getting disconnected ping timeout or sometimes i get disconnected transport close
I had the same problem.
The problem wasn't caused by the socket_io_client package.
When i update socket.io on my server side, the problem is solved.
Just run npm install socket.io#latest command on your node.js server.
According to the socket_io_client official doc, use this workaround if you are using https server:
class MyHttpOverrides extends HttpOverrides {
#override
HttpClient createHttpClient(SecurityContext context) {
return super.createHttpClient(context)
..badCertificateCallback =
(X509Certificate cert, String host, int port) => true;
}
}
void main() {
HttpOverrides.global = new MyHttpOverrides();
runApp(MaterialApp(
...
));
}

Cannot connect to socket.io connection in node.js

I'm new to node.js and, having worked through the relevant parts of the Wexler book, I am trying to create a simple stream using socket.io.
Here is my node.js server code:
const port = 3000,
dataIntervalMillis = 5000,
express = require("express"),
app = express(),
crypto = require('crypto');
const server = app
// .get("/", (req, res) => {
// res.send("Run this project by typing in <b>nodemon</b> in the node.js command prompt.");
// })
.listen(port, () => {
console.log(`RNG Server running on port number ${port}`);
}),
io = require("socket.io")(server);
io.on("connection", client => {
console.log("RNG client connected.");
io.emit("New RNG client connection.");
client.on("disconnect", () => {
console.log("RNG client disconnected.");
io.emit("RNG client disconnected.");
});
});
I have built a standalone Java application to test the stream:
//import java.io.BufferedReader;
import java.io.InputStream;
//import java.io.InputStreamReader;
//import java.io.PrintStream;
import java.net.Socket;
public class SimpleSocketClientExample {
public static void main(String[] args) {
String server = "localhost";
int port = 3000;
try {
// Connect to the server
System.out.println("Connect to server " + server + " on port " + port + "...");
Socket socket = new Socket( server, port );
System.out.println("...connected.");
//BufferedReader in = new BufferedReader( new InputStreamReader( socket.getInputStream() ) );
InputStream in = socket.getInputStream();
System.out.println("Reading byte...");
int b = in.read();
System.out.println("...byte read.");
// Close our streams
if (in != null) {
in.close();
}
if (socket != null) {
socket.close();
}
}
catch( Exception e ) {
e.printStackTrace();
}
}
}
The problem is that this client code hangs on the in.read() line.
The only console log from the server is RNG Server running on port number 3000. There is no RNG client connected in the server log, which indicates that the client has not connected (or has connected to something else).
I've tested my node.js app using online socket testers, and they don't seem to connect either - indicating the problem probably lays with my node.js server app.
Can anyone advise what I may have missed?
Turns out socket.io doesn't create a standard TCP socket.
My solution was to leave my client code untouched and change the Node.js server code to use the net library instead.
In case it might help anyone else that runs into the same issue, here's my new code:
const port = 3000;
const { createServer } = require('net');
const server = createServer();
// A counter to facilitate assigning of socket.id.
let counter = 0;
// An array of connected client sockets that we will broadcast to.
let sockets = {};
server.on('connection', (socket) => {
socket.id = counter++;
console.log(`A client has connected: ${socket.id}`);
// Catch errors so they don't stop the application.
socket.on('error', function () {
console.log(`Client error: ${socket.id}`);
delete sockets[socket.id];
});
// Set character encoding.
socket.setEncoding('utf8');
// Add socket to array.
sockets[socket.id] = socket;
// When connection ends, remove socket from array.
socket.on('end', data => {
console.log(`${socket.id} has disconnected`)
delete sockets[socket.id];
});
});
server.listen(port, () => {
console.log(`RNG Server running on port number ${port}`);
});

socket.io failing after refresh page in client side

I am using socket.io in a react - node project. I have a problem with the socket not refreshing when the page refreshes.
It works first as the server and the react dev server run for the first time. After using the socket ( emitting something from the server ), refreshing the browser page would result in an error in the web socket.js file :
WebSocket connection to
'ws://localhost:4000/socket.io/?EIO=3&transport=websocket&sid=XTE63CeWdp676cRXAAAF'
failed: Error during WebSocket handshake: Unexpected response code:
400
here is the code I use in client and server :
SERVER :
const express = require('express');
const socketconfig = require('./socket.io');
class Server {
constructor({ config, router, logger, }) {
this.config = config;
this.logger = logger;
this.express = express();
this.express.disable('x-powered-by');
this.express.use(router);
}
start() {
return new Promise((resolve) => {
const http = this.express
.listen(this.config.web.port, () => {
const { port } = http.address();
this.logger.info(`[p ${process.pid}] Listening at port ${port}`);
resolve();
});
var io = require('socket.io').listen(http,function () {
console.log("I AM CONNECTIONG")
});
this.freshio=io.sockets;
socketconfig.setOnConnection(this.freshio, ()=>{
console.log('Connexion COnditions are set');
});
socketconfig.setOnDisconnect(this.freshio, ()=>{
console.log('client disconnected');
});
this.clients = socketconfig.clients;
});
}
}
module.exports = Server;
the start() method would be called when the server is initiated.
the socketConfig file is just a toolkit for saving clients and setting conditions, it doesn't interfere with anything.
CLIENT :
import openSocket from 'socket.io-client';
let url = Store.config.socketserverurl + ":" + Store.config.socketserverport;
const socket = openSocket.connect(url);
Store is just the flux store that has the config files linked to it.
I have tried adding the webSockets method of using socket.io instead of the http method but that was in vain as an other problem spiraled.
what should I do ?

Unable to connect to socket IO locally in reactjs?

I am using nodeJs as backend and reactJs as my frontend the thing is I emitted a socket emit function from node
var server = require('http').createServer();
var io = require('socket.io')(server);
io.emit('quantity_check', 'KR')
now the issue is I'm unable to catch the emit
let serverUrl = 'localhost:3008'
const socket = socketIOClient(serverUrl);
socket.on("quantity_check", data => this.setState({ kiiii: data }));`
const socket = socketIOClient(serverUrl);
I'm checking this locally even i tried with my ip its not connecting I am not sure where the issue occurs
pc:nodejs and reactjs running on different ports
Can you post the code of you node server file and the react file where are you are listening to the sockets?. Anyway i hope that emit event is inside the connection
io.on('connection', function(socket) {
io.emit('quantity_check', 'KR')
}
and did you use the life cycle method componentDidMount to receive message
componentDidMount() {
socket.on("quantity_check", data => {
console.log(data);
});
}
Try something like this.
server
const server = require('http').createServer();
const io = require('socket.io')(server);
io.on('connect', (socket) => {
io.emit('quantity_check', 'KR');
});
Client(React side)
import io from 'socket.io-client';
const socket = io('http://localhost:3008');
export class App extends Component {
componentDidMount() {
socket.on('connect', () => {
console.log(socket.connected);
});
socket.on("quantity_checke", data => {
console.log(data);
});
}
render().......
}

Resources