ryo-ma / deno-websocket

🦕 A simple WebSocket library like ws of node.js library for deno
https://deno.land/x/websocket
MIT License
152 stars 17 forks source link

error: Uncaught (in promise) ConnectionReset: Socket has already been closed #18

Closed Josema closed 3 years ago

Josema commented 3 years ago

Hi, I'm getting this error and not sure why:

error: Uncaught (in promise) ConnectionReset: Socket has already been closed
      throw new Deno.errors.ConnectionReset("Socket has already been closed");
            ^
    at WebSocketImpl.enqueue (https://deno.land/std@0.88.0/ws/mod.ts:302:13)
    at WebSocketImpl.send (https://deno.land/std@0.88.0/ws/mod.ts:326:17)
    at WebSocketAcceptedClient.send (https://deno.land/x/websocket@v0.1.0/lib/websocket.ts:141:28)
    at send (file:///home/enzo/projects/spotifyfiesta/server/index.js:23:20)

My script

import { WebSocketServer } from './deps/websockets.js'
import { createNode } from './deps/dop.js'
import * as endpoints from './endpoints.js'
import { unsubscribeFiesta } from './store.js'
// import { MAX_MESSAGE_INTERVAL_SOCKET } from './const.js'
import { WS_PORT } from '../shared/config.js'
import { log } from '../shared/utils.js'
import './crons.js'

const wss = new WebSocketServer(WS_PORT)
wss.on('connection', (ws) => {
    log('ws connection', ws.webSocket.conn.remoteAddr)
    const client = createNode({})
    const send = (msg) => {
        if (ws.state === 1) {
            ws.send(msg)
        }
    }
    client.open(send, () => ({ ...endpoints }))
    ws.on('message', (message) => client.message(message))
    ws.on('close', () => {
        unsubscribeFiesta({ client })
        log('ws close')
    })
})

log('WebSocket server at ' + WS_PORT)
Josema commented 3 years ago

Never mind, I had to use !ws.isClosed instead of ws.state === 1