Vue中
第一步:安装插件
npm i socket.io-client -S
第二步:组件中引入使用
<template>
<div>
<el-button @click="handleEmit">发送</el-button>
</div>
</template>
<script setup lang='ts'>
import { io } from "socket.io-client";
const socket = io('http://localhost:6789', {
autoConnect: true,
})
const handleEmit = () => {
socket.emit('chatMessage', 'test-value', (response: any) => {
console.log(response, '发送消息,接收发送成功响应信息');
});
}
socket.on('chat message', function(msg) {
console.log('接收消息', msg);
});
</script>
nodejs中
第一步:安装插件
npm i socket.io --save
npm i express --save
第二步:在文件中引入使用
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, {
cors: {
origin: ['http://localhost:8999']
}
});
io.on('connection', (socket) => {
console.log('接收到客户端请求');
socket.on('chatMessage', (msg, callback) => {
console.log('客户端请求信息', msg);
callback('你请求成功了')
io.emit('chat message', {
status: 200,
data: 'result'
});
});
})
server.listen(6789, () => {
console.log('listening on *:6789');
});