當前位置: 首頁>>代碼示例>>TypeScript>>正文


TypeScript ws.Server類代碼示例

本文整理匯總了TypeScript中ws.Server的典型用法代碼示例。如果您正苦於以下問題:TypeScript Server類的具體用法?TypeScript Server怎麽用?TypeScript Server使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


在下文中一共展示了Server類的8個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的TypeScript代碼示例。

示例1: before

 before(async () => {
   let i = 0
   portB = getNewTestingPort()
   wss = new WebSocketServer({ port: portB })
   wss.on('connection', (ws:any) => {
     switch (i) {
       case 0:
         s1 = WS2PConnection.newConnectionFromWebSocketServer(ws, new (class TmpHandler implements WS2PMessageHandler {
           async handlePushMessage(json: any): Promise<void> {
           }
           async answerToRequest(json: any): Promise<WS2PResponse> {
             return { answer: 'world' }
           }
         }), new WS2PNoLocalAuth(), new WS2PNoRemoteAuth())
         s1.connect().catch(e => logger.error('WS2P: newConnectionFromWebSocketServer connection error'))
         break
       case 1:
         let j = 0
         s2 = WS2PConnection.newConnectionFromWebSocketServer(ws, new (class TmpHandler implements WS2PMessageHandler {
           async handlePushMessage(json: any): Promise<void> {
           }
           async answerToRequest(json: any): Promise<WS2PResponse> {
             return { answer: 'this is s2![j = ' + (j++) + ']' }
           }
         }), new WS2PNoLocalAuth(), new WS2PNoRemoteAuth())
         s2.connect().catch(e => logger.error('WS2P: newConnectionFromWebSocketServer connection error'))
         break
     }
     i++
   })
 })
開發者ID:duniter,項目名稱:duniter,代碼行數:31,代碼來源:ws2p_connection.ts

示例2: createClosingServer

export function createClosingServer(port: number, onDone?: () => void) {
  const wss = new WebSocket.Server({ port })
  wss.on('connection', () => {
    wss.close()
    onDone && onDone()
  })
}
開發者ID:chenrui2014,項目名稱:reactotron,代碼行數:7,代碼來源:create-closing-server.ts

示例3: test

test('plugins support send', async done => {
  const port = await getPort()
  const server = new WebSocket.Server({ port })

  let capturedSend: any

  // the plugin to extract the send function
  const plugin = reactotron => {
    capturedSend = reactotron.send
    return {}
  }

  // create the client, add the plugin, and connect
  const client = createClient({
    createSocket,
    port,
    onConnect: () => capturedSend(mock.type, mock.payload),
  }).use(plugin)

  // the server waits for the command
  server.on('connection', socket => {
    // fires the server receives a command
    socket.on('message', message => {
      const { type, payload } = JSON.parse(message.toString())
      if (type === 'client.intro') return
      expect(type).toEqual(mock.type)
      expect(payload).toEqual(mock.payload)
      done()
      server.close()
    })
  })

  client.connect()
})
開發者ID:chenrui2014,項目名稱:reactotron,代碼行數:34,代碼來源:plugin-send.test.ts

示例4: initialize

export function initialize(server: Server): void {

  log('Starting web socket server')

  const options: IServerOptions = { server }
  const wsServer = new WSServer(options)

  wsServer.on('error', error => {
    log(`Websocket error ${error}`)
  })

  wsServer.on('close', () => {
    log('Connection closed')
  })

  wsServer.on('connection', client => {

    log('Client connection')

    client.on('message', (data, flags) => {
      if (typeof data === 'string') {
        client.send(data.toUpperCase())
      } else {
        client.send(data)
      }

    })

    client.send('data')
    client.send(JSON.stringify({ complex: 'object' }))

  })

}
開發者ID:Edward-Lombe,項目名稱:elm-electron,代碼行數:34,代碼來源:websocket.ts

示例5: constructor

    constructor() {
        this.board = new ServerBoard();
        this.board.players = [];
        this.board.width = 1000;
        this.board.currentY = 0;
        ServerTimeUtils.start();
        setInterval(() => {
            this.board.tick();
        }, 1000 / 10);

        const wss = new Server({port: 7898});
        console.log('server open');

        wss.on('connection', (ws) => {
            ws.binaryType = "arraybuffer";
            let player = new ServerPlayer(ws);
            this.board.players.push(player);

            ws.on('message', (m: string) => {
                let message = JSON.parse(m) as Message;
                this.board.processMessage(player, message);
            });

            ws.on('close', () => {
                this.board.removePlayer(player);
            });
        });
    }
開發者ID:dested,項目名稱:OrbitalCrash,代碼行數:28,代碼來源:app.ts

示例6: Observable

 return new Observable(serverObserver => {
   console.info('started server...');
   let wss = new Server(options);
   wss.on('connection', connection => serverObserver.next(connection));
   return () => {
     wss.close();
   }
 }).share();
開發者ID:LongLiveCHIEF,項目名稱:aim,代碼行數:8,代碼來源:stock_server.ts

示例7: Server

 return new Rx.Observable(serverObserver => {
   console.info('started websocket server at port :' + options.port);  
   let wss = new Server(options);
   wss.on('connection', connection => serverObserver.next(connection));
   return () => {
     wss.close();
   }
 }).share();
開發者ID:ranjitjc,項目名稱:ts-express-webapi,代碼行數:8,代碼來源:ws-server.ts

示例8: express

;(async () => {
  type Pos = {x: number, y: number}
  // type DbVal = {[id: string]: Pos}

  // The store is a kv store mapping from client ID (incrementing numbers) => latest position.
  const store = await kvMem<Pos>()

  const app = express()
  app.use(express.static(`${__dirname}/public`))

  const server = http.createServer(app)
  const wss = new WebSocket.Server({server})

  let nextId = 1000

  wss.on('connection', async (socket, req) => {
    const id = `${nextId++}`

    const [reader, writer] = wrapWebSocket<BothMsg, BothMsg>(socket)
    const remoteStore = await connectMux<Pos>(reader, writer, store, false)

    // console.log(id, 'info', remoteStore.storeInfo)
    console.log(id, 'client connected')
    const sub = remoteStore.subscribe({type: I.QueryType.Single, q: true})

    reader.onClose = () => {
      console.log(id, 'client gone')
      // delete db[id]
      // console.log('db', db)
      rmKV(store, id)
    }

    for await (const val of subValues(I.ResultType.Single, sub)) {
      // console.log(id, 'cu', val)
      // await setKV(store, id, {x: val.x, y: val.y})
      await setKV(store, id, val)
      // console.log('db', db)
    }
  })

  const port = process.env.PORT || 2222
  server.listen(port, (err: any) => {
    if (err) throw err
    console.log('listening on', port)
  })


  if (process.env.NODE_ENV !== 'production') {
    const tcpServer = serveTCP(store)
    tcpServer.listen(2002, 'localhost')
    console.log('Debugging server listening on tcp://localhost:2002')
  }
})()
開發者ID:josephg,項目名稱:statecraft,代碼行數:53,代碼來源:server.ts


注:本文中的ws.Server類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。