Created
October 18, 2021 17:04
-
-
Save wobsoriano/79fa3be004f0a1b70f94e34dfbade897 to your computer and use it in GitHub Desktop.
Nuxt 3 + socket.io
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<script setup lang="ts"> | |
import { io } from 'socket.io-client' | |
const connected = ref(false) | |
onMounted(() => { | |
const socket = io(); | |
socket.on('connect', () => { | |
connected.value = socket.connected | |
}); | |
socket.on('disconnect', () => { | |
connected.value = socket.connected | |
}); | |
}) | |
</script> | |
<template> | |
<div>Connected: {{ connected }}</div> | |
</template> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// server/middleware/socket.ts | |
import type { IncomingMessage, ServerResponse } from 'http' | |
import { Server } from 'socket.io' | |
let server: any = null | |
export default (req: IncomingMessage, res: ServerResponse) => { | |
if (!server) { | |
// @ts-expect-error: Nuxt3 | |
server = res.socket?.server | |
const io = new Server(server); | |
io.on('connection', (socket) => { | |
console.log('Made socket connection'); | |
socket.on('msg', (msg) => { | |
console.log('Recived: ' + msg) | |
setTimeout(() => { | |
socket.emit('msg', `Response to: ${msg}`) | |
}, 1000) | |
}) | |
socket.on('disconnect', () => console.log('disconnected')) | |
}) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment