node模块socket.io简单使用(2022-12-09 记录)

在node环境下使用socket.io,需要在node服务端安装socket.io

客服端安装socket.io-client

服务端使用

const express = require("express")();
const http = require("http").createServer(express);
const io = require("socket.io")(http,{cors:true});    //    使用这个socket有跨域问题需要将cors设置为true

io.on("connect",(socket)=>{
    //......
})

在服务端项目中使用的时候需要在项目根目录bin下使用(我将文件拆分开来使用)

socket.js

module.exports = {
    getSocket:(server)=>{
        const io = require("socket.io")(server,{cors:true})
        
        io.on("connect",(socket)=>{
            console.log("connect");
        })
    }
}

bin/www

//在顶部添加
const {getSocket} = require("../socket.js")

//然后需要在当前文件的(http/https).createServer()的后面加上
getSocket(httpSerer)

客户端使用

安装socket.io-client

npm i socket.io-client

使用

import io from 'socket.io-client'

const socket = io("ws://127.0.0.1:3000");
socket.on('connect',()=>{
    alert(socket.connected)
})

或者使用cdn方式引入

<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.3.0/socket.io.js"></script>

使用

<script>
    const socket = io("ws://127.0.0.1:3000");
    socket.on('connect',()=>{
        console.log("connect");
    })
</script>

socket.io的事件类型(客户端)

connectFired upon connection (including a successful reconnection)
disconnectFired upon disconnection
connect_errorFired upon a connection error
connect_timeoutFired upon a connection timeout
reconnect_attemptFired upon an attempt to reconnect
reconnect_errorFired upon a reconnection attempt error
reconnect_failedFired when the client couldn’t reconnect within reconnectionAttempts
reconnectingAlias for “reconnect_attempt”
reconnectFired upon a successful reconnection
pingFired when a ping is sent to the server
pongFired when a pong is received from the server

 Nginx的socket.io配置

http {
  server {
    listen 3000; # 监听端口
    server_name io.yourhost.com; # 你的域名

    location / {
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header Host $host;

      proxy_pass http://nodes; # 你的转发链接 upstream nodes 跟这个有关系
        # 相当于 http://app01:3000;

      # enable WebSockets
      proxy_http_version 1.1;
      proxy_set_header Upgrade $http_upgrade;
      proxy_set_header Connection "upgrade";
    }
  }

  upstream nodes {
    # enable sticky session based on IP
    ip_hash;

    server app01:3000;
    server app02:3000;
    server app03:3000;
  }
}

详情请参考2022-12-12记(关于nginx配置socket.io的wss和ws代理(2022-12-12记)_StarCloud.的博客-CSDN博客)文章,关于wss和ws链接的nginx配置

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值