I am using Node.JS and I am using http to use an express server which then my WebSocket is on, but when I try to connect to the socket it gives me an 'Expected HTTP/' error.
My code:
const express = require('express');
const app = express();
const server = require('http').createServer(app);
app.get('/', (req, res) => {
res.send("Hello World!");
});
const wss = new WebSocket.Server({ server });
// web socket stuff here
server.listen(port, () => {
console.log(`HTTP Server started on port ${port}`);
});
And then on another Node project, I have this to connect:
const WebSocket = require('ws');
const ws = new WebSocket.WebSocket('ws://localhost:3000/ws');
Any help?
//my memory in this question was that
const WebSocket = require('ws');
const socket = new WebSocket.Server({ port: 2424, host: "localhost"});
socket.on('connection', function(ws, wss) {
var domain = wss.headers.origin;
//etc...
But maybe you have a front for communicate if is not the good response ?
Related
In my Node.js backend I have the following code which is supposed to set up the Socket.io connection:
const express = require("express");
const app = express();
const { createServer } = require("http");
const httpServer = createServer(app);
const port = 3001;
const io = require("socket.io")(httpServer, { cors: { origin: "*" } });
io.on("connection", (socket) => {
console.log("Connected!");
socket.on("join-room", (id) => {
socket.join(id);
console.log(`user joined room ${id}`);
});
});
Previously this was working, but for some reason it isn't anymore. When I started my server today I wasn't able to get Connected! logged to the console, nor was user joined room logged to the console when that event was triggered. Is there something wrong with how I'm establishing this connection?
I started my server but always redirect to nginx server, how to change??
i'm code with js for try connect host:
const http = require('http');
const requestListener = (req, res) => {
response.setHeader('Content-Type', 'text/html');
response.statusCode = 200;
response.end('<h1>Halo HTTP Server!</h1>');
}
const server = http.createServer(requestListener);
const port = 8080;
const host = 'localhost';
server.listen(port, host, () => {
console.log(`Server berjalan pada http://${host}:${port}`);
});
layout
I'm having a problem with testing the connection when I use https://localhost:3000/ it connects successfully but I want to use socket Io client on a different device on android application to be precise I searched it up and turns out localhost wont work I have to connect using ipv4 address well I tried it but didnt work - like this http http://192.168.XX.XX:3000 for example so what is the problem why doesnt it connect please help
server code:
var cors = require("cors");
const express = require("express");
const app = express();
const port = process.env.PORT || 3000 ;
const server = app.listen(port, () => {
console.log(`started on ${port}`);
})
const io = require('socket.io')(server, {
cors: { origin: "*" }
});
io.on('connection', (socket) => {
console.log('a user connected');
socket.on('message', (message) => {
console.log(message);
io.emit('message', `${socket.id.substr(0,2)} said ${message}` );
});
});
require("dotenv").config();
app.use(express.json());
app.use(cors());
//routes setup
const homeGetRoute = require("./routes/test.js");
app.use("/home", homeGetRoute);
app.use(cors());
I have the following lines of code in my index.js file:
const express = require('express');
const app = express();
const server = require('http').Server(app);
const io = require('socket.io').listen(server);
When I start my server with:
node --inspect server/index.js
I get:
TypeError: require(...).listen is not a function.
Any and all help appreciated!
You need http server.
The correct way to start a socket server is,
const express = require("express");
const http = require("http");
const app = express();
const server = http.createServer(app)
const socketio = require('socket.io')
const io = socketio(server);
io.on("connection", socket => {
console.log("connected");
socket.on("welcome", (data) => {
console.log("welcome message", data);
})
});
server.listen(3000, () => console.log(`listen on port ${port}`))
The client,
const io = require("socket.io-client");
let socket = io.connect("http://localhost:3000");
socket.emit("welcome", "Hi");
I have an existing project written in Express, where I've made a messaging system. Everything was working on POST/GET methods (to send and receive the messages).
I wanted to make them appear in real time, so I installed socket.io both on the client and server side. In my server.js I added these lines:
const http = require("http");
const io = require("socket.io");
const server = http.createServer();
const socket = io.listen(server);
and changed my app.listen(...) into server.listen(...).
Added also:
socket.on("connection", socket => {
console.log("New client connected");
socket.on('test', (test) => {
console.log('test-test')
});
socket.emit('hello', {hello:'hello!'});
socket.on("disconnect", () => console.log("Client disconnected"));
});
On the front part I put such code in the componentDidMount method:
const socket = socketIOClient();
socket.emit('test', {test:'test!'})
socket.on('hello', () => {
console.log('aaa')
})
Now I got 2 problems. Although the console.log() works correctly, I get an error on the React app:
WebSocket connection to 'ws://localhost:3000/sockjs-node/039/lmrt05dl/websocket' failed: WebSocket is closed before the connection is established.
Is that normal?
Also, when I change app.listen(...) into server.listen(...) in the server.js file, my routing stops working. All the POST and GET methods don't work, because the server is responding endlessly. Is that possible to use the socket.io just on a specific method in a specific routing file?
I keep my routes that way: app.use('/api/user', user); where user is a router file.
UPDATE:
full server.js require:
const express = require('express');
const mongoose = require('mongoose');
const dotenv = require('dotenv');
const bodyparser = require('body-parser');
const passport = require('passport');
const user = require('./routes/api/v1/User');
const company = require('./routes/api/v1/Company');
const http = require("http");
const io = require("socket.io");
const app = express();
dotenv.config();
app.use(passport.initialize());
require('./config/seed');
require('./config/passport')(passport);
const server = http.createServer();
const socket = io.listen(server);
You're not initializing server properly. Try making the following change
// const server = http.createServer();
const server = http.createServer(app);
and make sure you listen on server and not io
server.listen(PORT_GOES_HERE)
[UPDATE]
Working Example:
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
server.listen(80);
// WARNING: app.listen(80) will NOT work here!
// DO STUFF WITH EXPRESS SERVER
app.get('/', function (req, res) {
res.sendFile(__dirname + '/index.html');
});
io.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
For more details check this: https://socket.io/docs/