码迷,mamicode.com
首页 > Web开发 > 详细

nodejs websocket server

时间:2017-10-07 17:31:59      阅读:201      评论:0      收藏:0      [点我收藏+]

标签:creat   list   github   bsp   eth   hello   lis   send   http   

安装:

npm install ws

npm install ws –save   // 安装到工程目录

API使用:

const express = require(‘express‘);

const http = require(‘http‘);

const url = require(‘url‘);

const WebSocket = require(‘ws‘);

 

const app = express();

 

/**

 * WebSocket服务端例子

 *  框架:https://github.com/websockets/ws

 */

app.use(function (req, res) {

    res.send({msg: "hello"});

});

 

const server = http.createServer(app);

//noinspection JSAnnotator

const wss = new WebSocket.Server({server});

 

function testWebSocketServerApi() {

    wss.on(‘connection‘, function connection(ws, req) {

        const location = url.parse(req.url, true);

        const ip = req.connection.remoteAddress;

        const port = req.connection.remotePort;

        console.log(ip + " " + port);

 

        ws.on(‘message‘, function incoming(message) {

            console.log(‘received: %s‘, message);

        });

 

        ws.on(‘close‘, function (params) {

            console.log(‘params: %s‘, message);

        });

 

        ws.send(‘something‘);

    });

 

    server.listen(8080, function listening() {

        console.log(‘WebSocket Listening on %d‘, server.address().port);

    });

 

    const WSS = new WebSocket.Server({ port: 8081 });

 

    WSS.on(‘connection‘, function connection(ws) {

        ws.on(‘message‘, function incoming(message) {

            console.log(‘received: %s‘, message);

        });

 

        ws.send(‘something‘);

    });

}

 

 

参考:

     websockets/ws

nodejs websocket server

标签:creat   list   github   bsp   eth   hello   lis   send   http   

原文地址:http://www.cnblogs.com/zhen-android/p/7634888.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!