SocketIO 没有实时更新?

SocketIO not updating in real time?

我正在努力适应 SocketIO 和实时数据传输。

我做了这个简单的前端实现,它向服务器发出一个事件,服务器更新我的年龄加 10。但这不是更新我从前端获得的多个连接,它只是更新 window 我举办活动的地方。

客户端

function handleEmit() {
        console.log('Emitting...', person);
        socket.emit('new-ops', JSON.stringify(person));
    }

    React.useEffect(() => {
        socket.on('new-remote-ops', (data) => {
            console.log('Listening new-remote-ops');
            setPerson({ ...JSON.parse(data) });
        });
    }, [])

服务器端

io.on('connect', socket => {
    console.log('a user connected');
    socket.on('new-ops', data => {
        const data2 = JSON.parse(data);
        socket.emit('new-remote-ops', JSON.stringify({ name: data2.name, age: data2.age + 10 }), (err) => console.log(err));
    })
})

编辑: package.json 服务器的文件

{
  "name": "server",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "dependencies": {
    "express": "^4.17.2",
    "socket.io": "^4.4.0"
  },
  "devDependencies": {},
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node ."
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}

package.json 客户端文件:

{
  "name": "client",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^5.16.1",
    "@testing-library/react": "^12.1.2",
    "@testing-library/user-event": "^13.5.0",
    "react": "^17.0.2",
    "react-dom": "^17.0.2",
    "react-scripts": "5.0.0",
    "socket.io-client": "^4.4.0",
    "web-vitals": "^2.1.2"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

编辑#2: 正如 Pascal 的回答所述,我将 socket.emit() 更改为 io.emit() 现在两个连接都收到了一些东西,但他们没有收到我想要的数据。正如我附加的服务器代码中所述,我想将 10 添加到我收到的年龄(初始值为 1),因此当我单击按钮时它应该将年龄从 1 更新为 1 + 10 等等(是的,我正在更新状态,但即使我 console.log() 我收到的数据,它在客户端也不是 1 + 10,而是在服务器端)

更改后我在服务器上的 io 实现

io.on('connect', socket => {
    console.log('a user connected');
    socket.on('new-ops', data => {
        io.emit('new-remote-ops', { name: data.name, age: data.age + 10 });
    })
})

我的客户端代码

const App = () => {
    const [person, setPerson] = React.useState({
        name: 'Sergio',
        age: 1
    });
    const [socketConnected, setSocketConnected] = React.useState(false);

    function handleEmit() {
        console.log('Emitting...', person);
        socket.emit('new-ops', person);
    }

    React.useEffect(() => {
        socket.on('new-remote-ops', (data) => {
            console.log(data);
            setPerson({ name: data.name, age: data.age });
        });
    }, [])

    React.useEffect(() => {
        if (!socket) return;

        socket.on('connect', () => setSocketConnected(true))

        socket.on('disconnect', () => setSocketConnected(false))
    }, [socket])
    return (
        <>
            <div>React App</div>
            <span>{socketConnected ? 'Connected' : 'Disconnected'}</span>
            <div />
            <button onClick={handleEmit}>Emit</button>
            <br />
            <span>{person.name}, {person.age}</span>
        </>
    )
}

使用socket.broadcast/io.emit向所有连接发送数据

在您的服务器端代码中...

socket.on('new-ops', data => {
  const data2 = JSON.parse(data);
  socket.emit('new-remote-ops', JSON.stringify({
    name: data2.name,
    age: data2.age + 10
  }), (err) => console.log(err));
})

...您接收和发送数据到同一个 socket。这将始终相同 socket.

如果您想从单个套接字接收数据但要响应所有可用连接,则必须使用 broadcast (here) or io.emit (here)

例子

// everyone gets it but the sender
socket.broadcast.emit("an event", { some: "data" });

// everyone gets it
io.emit("an event sent to all connected clients"); // main namespace

Socket.io版本4.x