zoukankan      html  css  js  c++  java
  • HTML5-WebSocket-初探

    1.环境准备

    主要是用《HTML5 程序设计》(第二版)作为学习参考资料。但是上面用的WebSocket服务器是用python写的。偶不懂python,于是得找另外一个替代实现,这里适用node.js的ws模块。

    相关资料有:WebSocket协议node.js入门

    这里特别说明一下node.js的调试方法。目前比较好的方式是适用inspector的方式。

    首先安装node-inspector,运行命令npm install -g node-inspector,参数g没验证过是否必须,应该是全局的意思,就是说运行它不用进入它的目录。

    打开一个命令行窗口,运行node-inspector [WebSocket.js]。

    这个访问地址非常坑爹,才不是访问0.0.0.0,而是127.0.0.0

    接着打开另一个命令行窗口,用如下方式运行需要调试的js文件:node --debug-brk WebSocket.js

    打开浏览器,输入http://127.0.0.1:8080/debug?port=5858,然后就可以看到调试界面

    用另外一个页签打开客户端网页。

    2.简单例子

    1 var WebSocketServer = require('ws').Server
    2   , wss = new WebSocketServer({port: 8888});
    3 wss.on('connection', function(ws) {
    4     ws.on('message', function(message) {
    5         console.log('received: %s', message);
    6     });
    7     ws.send('something');
    8 });
    服务端WebSocket.js
     1 <script>
     2 var wsServer = 'ws://localhost:8888/';
     3 
     4 var websocket = new WebSocket(wsServer);
     5 websocket.onopen = function(e){
     6 websocket.send('ws opened');
     7 };
     8 websocket.onmessage = function(e){
     9 console.log(e);
    10 };
    11 </script>
    客户端WebSocket.html

    参考自官网,ws模块的文档

  • 相关阅读:
    vue源码分析—Vue.js 源码目录设计
    vue源码分析—认识 Flow
    在Windows上安装配置MongoDB
    mongoDB概述
    Could not load file or assembly Microsoft.Web.Infrastructure
    配置错误 不能在此路径中使用此配置节(转)
    VS2013快捷键大全
    Create new tool for CSV
    How to get http response.
    C#中Split用法
  • 原文地址:https://www.cnblogs.com/var-iable/p/3155795.html
Copyright © 2011-2022 走看看