【问题标题】:How to create socket.io server without using http module?如何在不使用 http 模块的情况下创建 socket.io 服务器?
【发布时间】:2021-07-24 14:39:10
【问题描述】:

http 模块来创建服务器并将快速应用程序上下文传递给它,然后监听它。 我见过 express'app.listen 返回一个服务器上下文 现在如何使用app.listen的上下文创建一个socket.io服务器

我已经尝试了下面的代码,但它不起作用。

onst express = require('express')
const socket = require('socket.io')

const PORT = 5000

const app = express()

const server = app.listen(PORT, () => console.log(`Server started on port ${PORT}`))

const io = new socket.Server(server)

io.on("connection", function(socket) {
    console.log("A new socket has joined: " + socket.id)

    socket.on("hello", function(data) {
        console.log(data);
    })
})

代码启动没有抛出任何错误,但套接字服务器没有启动

【问题讨论】:

    标签: node.js express socket.io


    【解决方案1】:

    您确定您的套接字服务器没有启动吗?可能是您在客户端有问题...

    我添加了带有客户端代码的index.html,它已成功连接到后端。

    结帐:https://github.com/theanurin/*.68511005

    附言

    Server started on port 5000
    A new socket has joined: IqEjjc0dBHYSHqpMAAAB
    

    【讨论】:

    • 是的,问题出在客户端,但我不明白为什么会发生这种情况,它没有通过邮递员连接到 websocket
    • 我以前从未使用过 Postman 作为 SocketIO 客户端...我现在已经用我的示例进行了尝试。建立连接没有任何问题。我在自述文件中添加了我的经验github.com/theanurin/*.68511005
    • 帮了大忙!
    【解决方案2】:

    Socket IO 的文档中有一个关于integrating with Express 的部分。他们的示例代码如下所示:

    const express = require('express');
    const app = express();
    const http = require('http');
    const server = http.createServer(app);
    const { Server } = require("socket.io");
    const io = new Server(server);
    
    app.get('/', (req, res) => {
      res.sendFile(__dirname + '/index.html');
    });
    
    io.on('connection', (socket) => {
      console.log('a user connected');
    });
    
    server.listen(3000, () => {
      console.log('listening on *:3000');
    });
    

    虽然仍然直接使用http 模块,但您也许可以将http.createServer(app) 替换为您的app.listen 调用。请注意,我很确定 app.listen 实际上在后台使用 http.createServer。根据their documentation 的说法。

    【讨论】:

    • 是的,在这种情况下如何避免http.createServer?我相信我对一些文章或一些解释如何使用 express 本身创建 socket.io 服务器的 * 答案有生动的记忆
    • @SwapnilSoni 真的有必要吗?如果你只使用app.listen(PORT),它只会在内部使用http.createServer。但根据他们文档中的示例,假设他们没有对server 做一些影响server.listen 的骇人听闻的事情,使用io = new Server(server) server = app.listen(PORT) 应该可以工作。
    • 实际上是的,我需要在 socket.io 中使用 express'Server 上下文我知道每个人都建议使用 http 模块,但我在一年前在某个地方看到过,现在我在看到它的地方迷路了.我实际上尝试了该代码解决方案,它确实在不使用http 的情况下工作,所以在论坛上挖掘之后,我仍然没有找到确切的答案。所以我发布了自己
    【解决方案3】:

    我与 react native 'socket.io-client' 建立了连接,你的代码对我有用

    这是我的反应原生代码

    import React,{ Component } from "react";
    import {View,TextInput,Text,StyleSheet} from 'react-native'
    import io from "socket.io-client";
    export default class ChatApp extends Component{
     constructor(props) {
        super(props);
        this.state = {
           chatMessage: "",
           chatMessages: []
        };
     }
     componentDidMount() {
        this.socket = io("http://127.0.0.1:5000");
         this.socket.on("hello", msg => {
               this.setState({ chatMessages: [...this.state.chatMessages, msg]   
          });
       });
     }
    submitChatMessage() {
        this.socket.emit('hello', this.state.chatMessage);
        this.setState({chatMessage: ''});
    }
    render() {
        const chatMessages = this.state.chatMessages.map((chatMessage,index) => (
          <Text key={index} style={{borderWidth: 2, top: 500}}>{chatMessage}</Text>
        ));
    
        return (
          <View style={styles.container}>
            {chatMessages}
            <TextInput
              style={{height: 40, borderWidth: 2, top: 500}}
              autoCorrect={false}
              value={this.state.chatMessage}
              onSubmitEditing={() => this.submitChatMessage()}
              onChangeText={chatMessage => {
                this.setState({chatMessage});
              }}
            />
          </View>
        )
      }
    }
    
    const styles = StyleSheet.create({
      container: {
      height: 400,
      flex: 1,
      },
    });
    

    【讨论】:

      最近更新 更多