使用socket.io-client库从客户端向套接字服务器发送数据

时间:2019-07-28 08:25:03

标签: reactjs socket.io

我正在尝试使用socket.io-client库将数据从React客户端发送到Express服务器。但是,我不明白该怎么做。

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

但这对我不起作用。这是控制台输出

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

1 个答案:

答案 0 :(得分:0)

我发现了问题。将React客户端代码更改为以下内容后,该问题已修复,并且能够在客户端和服务器之间传输数据

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

 componentDidMount() {
    const session = getSession() || {};
    socket.emit("data", session);
 }
}