博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
websocket试用
阅读量:6887 次
发布时间:2019-06-27

本文共 4684 字,大约阅读时间需要 15 分钟。

hot3.png

websocket

1.通过websocket协议握手
2.后续通过tcp流方式交互

可以作为一个协议简介

在PC上试用,winxp,软件包选用了WebSocket-Node,websocket协议的nodejs扩展包

安装:
* npm install -g node-gyp
* npm install websocket

* server端代码(ws_demo_server.js)

半抄半改

// http://ejohn.org/blog/ecmascript-5-strict-mode-json-and-more/"use strict";// Optional. You will see this name in eg. 'ps' or 'top' commandprocess.title = 'node-chat';// Port where we'll run the websocket servervar webSocketsServerPort = 9000;// websocket and http serversvar webSocketServer = require('websocket').server;var http = require('http');/** * Global variables */// latest 100 messagesvar history = [ ];// list of currently connected clients (users)var clients = [ ];/** * HTTP server */var server = http.createServer(function(request, response) {    // Not important for us. We're writing WebSocket server, not HTTP server});server.listen(webSocketsServerPort, function() {    console.log((new Date()) + " Server is listening on port " + webSocketsServerPort);});/** * WebSocket server */var wsServer = new webSocketServer({    // WebSocket server is tied to a HTTP server. WebSocket request is just    // an enhanced HTTP request. For more info http://tools.ietf.org/html/rfc6455#page-6    httpServer: server,    autoAcceptConnections: false});function msg_history(userName, friend, msg){    var history = {        type: 'message',        time: (new Date()).getTime(),        msg: msg,        user: userName,        friend: friend,    };    return history;}function reg_user(userName, host, port) {  // put logic here to detect whether the specified origin is allowed.  return true;}// This callback function is called every time someone// tries to connect to the WebSocket serverwsServer.on('request', function(request) {    console.log((new Date()) + ' Connection from origin ' + request.origin + '.');    // accept connection - you should check 'request.origin' to make sure that    // client is connecting from your website    // (http://en.wikipedia.org/wiki/Same_origin_policy)    var connection = request.accept(null, request.origin);     // we need to know client index to remove them on 'close' event    var index = clients.push(connection) - 1;    var userName = false;    console.log((new Date()) + ' Connection accepted.');    // send back chat history    if (history.length > 0) {        connection.sendUTF(JSON.stringify( { type: 'history', data: history} ));    }    // user sent some message    connection.on('message', function(message) {        if (message.type === 'utf8') { // accept only text            if (userName === false) { // first message sent by user is their name                            // remember user name                var msgObj = JSON.parse(message.utf8Data);                userName = msgObj['data']['userName'];                console.log((new Date()) + ' User : ' + userName );                // get random color and send it back to the user                var msg = msg_history(userName, msgObj['data']['userFirend'], msgObj['data']['talkMsg']);                connection.sendUTF(JSON.stringify(msg));                            } else { // log and broadcast the message                console.log((new Date()) + ' Received Message from ' + userName + ': ' + message.utf8Data);                // we want to keep history of all sent messages                var msgObj = JSON.parse(message.utf8Data);                var msg = msg_history(msgObj['data']['userName'], msgObj['data']['userFirend'], msgObj['data']['talkMsg']);                history.push(msg);                history = history.slice(-100);                // broadcast message to all connected clients                var json = JSON.stringify(msg);                for (var i=0; i < clients.length; i++) {                    clients[i].sendUTF(json);                }            }        }else if (message.type === 'binary') {            console.log('Received Binary Message of ' + message.binaryData.length + ' bytes');            connection.sendBytes(message.binaryData);        }else {            console.log('Received Unknow Type Message');            connection.sendBytes('Received Unknow Type Message');        }    });    // user disconnected    connection.on('close', function(connection) {        if (userName !== false ) {            console.log((new Date()) + " Peer "                + connection.remoteAddress + " disconnected.");            // remove user from the list of connected clients            clients.splice(index, 1);            // push back user's color to be reused by another user        }    });});

* clien端代码(ws_demo_client.html)

(也是半抄半改,chrom下OK,测试要多开几个页面)

昵称 :
发给朋友:
内容 :

转载于:https://my.oschina.net/kakablue/blog/207996

你可能感兴趣的文章
如何获取name属性相同的input框中的值
查看>>
java的应用
查看>>
vim命令用法
查看>>
spring的工作原理?
查看>>
ceph配置日志使用独立分区
查看>>
Maven介绍及安装
查看>>
汶川大地震中的SAP成都研究院
查看>>
[官网翻译]RabbitMQ基本消息队列使用
查看>>
图书管理系统【JavaWeb:用户、购买、订单模块、添加权限】
查看>>
精讲Redis服务架构分析与搭建
查看>>
MySQL主从介绍及主从配置
查看>>
以太经典合作社(ECC)获得Digital Finance Group捐赠
查看>>
2018-5-13
查看>>
mysql卸载了如何恢复数据或mysql迁移数据库
查看>>
shell实例100例《十》
查看>>
Django之ORM多对多增册改查
查看>>
复习0610—Python数据类型
查看>>
tomcat 学习笔记之 Session管理
查看>>
attention理解笔记
查看>>
Linux 笔记
查看>>