Ad

Sending Data From Client To Socket Server Using Socket.io-client Library

- 1 answer

I am trying to send data from React client to Express server using the socket.io-client library. But, I am unable to understand how can this be done.

server.js

const express = require("express");
const http = require("http");
const socketio = require("socket.io");
const app = express();

const server = http.createServer(app);
const io = socketio(server);
server.listen(3000);

var connectedUsers = new Set();

io.on("connect", function(socket) {
  var socketId = socket.id;
  console.log("ADDING :: " + socket.id);
  connectedUsers.add(socket);
  console.log("length of usersList " + connectedUsers.size);
  socket.on("data", data => {
    console.log("received session data");
    console.log(data.session);
  });
  socket.once("disconnect", function() {
    console.log("LEAVING :: " + socket.id);
    connectedUsers.delete(socket);
    console.log("length of usersList " + connectedUsers.size);
  });
});

socketConnection.js

import io from "socket.io-client";

let socket = io.connect("http://localhost:3000");

console.log(socket);

export default socket;

reactClient.js

class Home extends Component {
  constructor(props) {
    super(props);
    this.state = {
      term: "",
      searchIconClicked: false,
      eventKey: 1
    };
  }

  componentDidMount() {
    const session = getSession() || {};
    socket.on("connect", function(socket) {
      console.log("connected to the server");
    data = {
        session: session,
        state: state

            }
      socket.emit("data", data);
    });
}

But this does not work for me. Here is the console output

bundle.js:150635 GET http://localhost:3000/socket.io/?EIO=3&transport=polling&t=MmthEJc net::ERR_CONNECTION_REFUSED
Request.create @ bundle.js:150635
Request @ bundle.js:150537
XHR.request @ bundle.js:150464
XHR.doPoll @ bundle.js:150494
Polling.poll @ bundle.js:74172
Polling.doOpen @ bundle.js:74117
Transport.open @ bundle.js:38330
Socket.open @ bundle.js:149843
Socket @ bundle.js:149716
Socket @ bundle.js:149623
Manager.open.Manager.connect @ bundle.js:73642
(anonymous) @ bundle.js:73956

Invalid Host/Origin header
error @ bundle.js:84210
onmessage @ bundle.js:86117
EventTarget.dispatchEvent @ bundle.js:86297
(anonymous) @ bundle.js:87014
SockJS._transportMessage @ bundle.js:87012
EventEmitter.emit @ bundle.js:86213
WebSocketTransport.ws.onmessage @ bundle.js:89088
Ad

Answer

I found the issue. After changing the React client code to the below the issue is fixed and able to transmit the data between the client and server

class Home extends Component {
   constructor(props) {
     super(props);
     this.state = {
     term: "",
     searchIconClicked: false,
     eventKey: 1
 };
 }

 componentDidMount() {
    const session = getSession() || {};
    socket.emit("data", session);
 }
}
Ad
source: stackoverflow.com
Ad