I am creating a react native app and and I'm trying to connect my client app to my server. I am using socket-io and I'm unsuccessful in connecting the two so far. Here is my code on the client:
import SocketIOClient from 'socket.io-client';
(...)
if (result.type === "success") {
console.log("Here 1");
this.socket = SocketIOClient('http://localhost:1997');
this.socket.emit('test', 'Hello world!');
console.log("Here 2");
}
And this code outputs "Here 1" "Here 2"
My Server code is as following:
let express = require('express');
let http = require('http')
let socketio = require('socket.io');
var app = express();
var server = http.Server(app);
var websocket = socketio(server);
let port = 1997;
server.listen(port, () => console.log('listening on *:' + port));
websocket.on('connection', (socket) => {
console.log("Client joined on " + socket.id);
websocket.on('test', function(data){
console.log('Data Receieved: ' + data);
});
});
This code outputs "listening on *:1997" and then nothing else even when the client code runs. Please help I'm not sure what I'm doing wrong.
I had the same issue and changing "localhost" to the actual ip, worked like a charm for me.
So change
this.socket = SocketIOClient('http://localhost:1997');
To
this.socket = SocketIOClient('http://192.168.xxx.xxx:1997');
I got the answer from here:
Using Socket.io with React Native and not working
Related
I am getting cross origin headers error despite running cors library, or simply a 404 not found while polling in the console.
The project structure looks like this
My goal is to have the little chat widget on every view. I will include this to the other views as EJS partial.
I am not sure what I going wrong I have tried to run Express on port 5000 and Socket IO on 8080 or 3000, all different combinations have not yielded anything good.
APP.JS looks like this
const { check } = require('express-validator');
const express = require("express");
const session = require("express-session");
const MongoDBStore = require("connect-mongodb-session")(session);
const config = require("config");
const flash = require('express-flash');
const cookieParser = require('cookie-parser');
const nodemailer = require("nodemailer");
const Mailgen = require("mailgen");
const dotenv = require('dotenv');
dotenv.config();
const appController = require("./controllers/appController");
const isAuth = require("./middleware/is-auth");
const connectDB = require("./config/db");
const mongoURI = config.get("mongoURI");
const bodyParser = require('body-parser');
var cors = require('cors') // This should help, but does nothing
const app = express();
const http = require('http').Server(app); // I suspect the mistake is in these lines
const io = require('socket.io')(http,
{
cors: {
origin: "http://localhost:5000", // Does nothing
credentials: true
}})
connectDB();
const store = new MongoDBStore({
uri: mongoURI,
collection: "mySessions",
});
app.use(cors({origin: '*'})) // Also seems not to be working
app.set("view engine", "ejs");
app.use(express.urlencoded({ extended: true }));
//Middleware and Routes
io.sockets.on('connection', function(socket) {
console.log("hello") // never happened
socket.on('username', function(username) {
console.log("hello") // never happened
socket.username = username;
io.emit('is_online', '🔵 <i>' + socket.username + ' join the chat..</i>');
});
socket.on('disconnect', function(username) {
io.emit('is_online', '🔴 <i>' + socket.username + ' left the chat..</i>');
})
socket.on('chat_message', function(message) {
io.emit('chat_message', '<strong>' + socket.username + '</strong>: ' + message);
});
});
app.listen(5000, console.log("App Running on http://localhost:5000"));
And the front end partial EJS looks like this
<ul id="messages"></ul>
<form action="/" method="POST" id="chatForm">
<input id="txt" autocomplete="off" autofocus="on" oninput="isTyping()" placeholder="type your message
here..." /><button>Send</button>
</form>
The rest of the front end page looks like this
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/3.0.4/socket.io.js" integrity="sha512-aMGMvNYu8Ue4G+fHa359jcPb1u+ytAF+P2SCb+PxrjCdO3n3ZTxJ30zuH39rimUggmTwmh2u7wvQsDTHESnmfQ==" crossorigin="anonymous"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<style> etcetc
<%- include ('./partialChatWidget.ejs') %>
And the JS
<Script>
var socket = io.connect('http://localhost:5000', { transport : ['websocket'] } );
$('form').submit(function(e){
e.preventDefault();
socket.emit('chat_message', $('#txt').val());
$('#txt').val('');
return false;
});
socket.on('chat_message', function(msg){
$('#messages').append($('<li>').html(msg));
});
socket.on('is_online', function(username) {
$('#messages').append($('<li>').html(username));
});
var username = prompt('Please tell me your name');
socket.emit('username', username);
</script>
So what is going wrong here, do I need 2 servers on different ports or 2 instances, I always thought socket IO borrows the http server , not the express instance.
Thanks for helping me out. I might add I get the cross origin errors when I try to run on 2 different ports. Else I get 404 not found in the console. The page and the partial and the initial JS(Jquery) run.
After a lot of back and forth....
Just make sure to load the front end link for socket IO right in the head section asap.
And do include this part on the front end
var socket = io.connect('http://localhost:5000', { transport : ['websocket'] } );
Definitely include this on the server side, this cant hurt, unless you want to block some pages from CORS access
app.use(cors({origin: '*'}))
The next 2 steps made it all work.
const app = express();
const http = require('http').Server(app);
const io = require('socket.io')(http,
{
cors: {
origin: "http://localhost:5000 {this is the port of your back end app, not for the socket IO port }",
credentials: true
}})
And finally, indeed, 2 servers.
const server = http.listen(8080, function() {
console.log('listening on *:8080');
});
app.listen(5000, console.log("App Running on http://localhost:5000"));
Took me a while, but now everything is clear once and for all(I hope)
app.use((req,res, next)=>{
res.setHeader('Access-Control-Allow-Origin',"http://localhost:3000");
res.setHeader('Access-Control-Allow-Headers',"*");
res.header('Access-Control-Allow-Credentials', true);
next();
});
use this code
and install the older socket.io version 2.3.0
try this code
`const server = app.listen(PORT,()=>console.log(`listening on port ${PORT}`));
io = require('socket.io').listen(server);
io.on('connection', (socket) => {
console.log('a user connected');
});`
I am using socket.io both (server API and client API) on Node.js as client and server. This is possible as specified in the docs). I am not using any particular frameworks except Express and followed the official guide for using socket.io with it.
On the server side I have:
const express = require("express");
const app = express();
const http = require("http");
server = http.Server(app);
const io = require("socket.io")(server) //server listens on "http://localhost:3001
io.on("connection", socket => {
console.log("server says: someone connected");
});
On the client side I have:
const io = require("socket.io-client")("http://localhost:3001");
io.on("connect", () => {
console.log("client says: connected");
});
Until here everything works fine... Now when adding namespaces nothing seem to work anylonger. I followed the official guide and ended up with the following:
On the server side I have:
const express = require("express");
const app = express();
const http = require("http");
server = http.Server(app);
const io = require("socket.io")(server) //server listens on "http://localhost:3001
const nsp = io.of('/my-namespace');
nsp.on("connection", socket => {
console.log("server says: someone connected");
});
On the client side I have:
const io = require("socket.io-client")("http://localhost:3001");
const socket = io('/my-namespace');
socket.on("connect", () => {
console.log("client says: connected");
});
But the after the introduction of namespaces nothing seems to work... What am I missing?!
Thanks I am completely lost
I was following the second example here:
https://github.com/socketio/socket.io-client
and trying to connect to a website that uses websockets, using socket.io-client.js in node.
My code is as follows:
var socket = require('socket.io-client')('ws://ws.website.com/socket.io/?EIO=3&transport=websocket');
socket.on('connect', function() {
console.log("Successfully connected!");
});
Unfortunately, nothing gets logged.
I also tried:
var socket = require('socket.io-client')('http://website.com/');
socket.on('connect', function() {
console.log("Successfully connected!");
});
but nothing.
Please tell me what I'm doing wrong. Thank you!
Although the code posted above should work another way to connect to a socket.io server is to call the connect() method on the client.
Socket.io Client
const io = require('socket.io-client');
const socket = io.connect('http://website.com');
socket.on('connect', () => {
console.log('Successfully connected!');
});
Socket.io Server w/ Express
const express = require('express');
const app = express();
const server = require('http').Server(app);
const io = require('socket.io')(server);
const port = process.env.PORT || 1337;
server.listen(port, () => {
console.log(`Listening on ${port}`);
});
io.on('connection', (socket) => {
// add handlers for socket events
});
Edit
Added Socket.io server code example.
I'm trying to connect to a nodejs server over a websocket connection but can't get anything to work.
My server.js looks like this:
var app = require('express')();
var http = require('http').createServer(app);
var io = require('socket.io', {
transports: ['websocket']
})(http);
var server_port = process.env.PORT || 8080
var server_ip_address = process.env.IP || '0.0.0.0'
app.listen(server_port, server_ip_address, function () {
console.log('listening on ' + server_ip_address + ":" + server_port);
});
My client.js (running on a raspberry pi also running nodejs) is:
var io = require('socket.io-client');
var socket = io.connect('http://<app-url>',
{
reconnect: true,
transports: ['websocket']
}
);
socket.on('connect', function(socket) {
console.log('Connected!');
});
I've also tried on openshift v2 (ports 8000 and 8443) and v3 and no luck there.
If anyone has done this recently please let me know how, thanks!
When debugging the client I get the message:
engine.io-client:socket socket close with reason: "transport error"
and on the server:
heroku[router]: at=error code=H13 desc="Connection closed without response"
It looks like a strange bug that happens sometimes, you should be able to get through by adding the path of your client library in the options like so :
var socket = io.connect('http://<app-url>:8080',
{
reconnect: true,
transports: ['websocket'],
path: "/lib/socket.io.js" //use the relevant path for your file
}
);
But you seem to be using the default options anyway, so you could just do :
var socket = io.connect();
Ok, it's working now. I modified the example in the heroku docs
I'm not quite sure why my server config doesn't work, but the following does work:
server.js
var express = require('express');
var socketIO = require('socket.io');
var path = require('path');
var PORT = process.env.PORT || 3000;
var app = express();
var server = app.listen(PORT, () => console.log(`Listening on ${ PORT }`));
var io = socketIO(server);
io.on('connection', (socket) => {
console.log('Client connected');
socket.on('disconnect', () => console.log('Client disconnected'));
});
client.js (xShirase was right in saying I needed the correct path here...)
var io = require('socket.io-client');
var socket = io.connect('https://<url>',
{reconnect: true, transports : ['websocket'], path: '/socket.io'});
socket.on('connect', function (socket) {
console.log('Connected!');
});
I'm trying this simple example:
Server:
app = require('express.io')()
app.http().io()
app.io.on('connection', function(socket){
console.log('connection')
})
app.listen(50000)
Client:
var io = require('socket.io-client').connect('http://localhost:50000')
io.on('connect', function (sock) {
console.log("socket connected")
})
Neither 'connection' nor 'socket connected' appears in nodejs console
However separate express and socket.io server works like a charm:
var app = require('express')()
var http = require('http').Server(app)
var io = require('socket.io')(http)
io.on('connection', function(socket){
console.log('connection')
})
http.listen(50000)
I'd like to get it done with express.io for educational purposes, but there is no forum, no archives, ...nowhere to ask