美文网首页
websocket初探学习分享

websocket初探学习分享

作者: 一支桨 | 来源:发表于2019-03-23 14:45 被阅读0次

本文主要是使用的心得,参考的网址是websocket,本例中使用的是Websocket-Node 服务器模式,本地全局安装node即可
服务端文件,本文命名为socketserver.js ,代码如下:

var WebSocketServer = require('websocket').server;
var http = require('http');

var server = http.createServer(function(request, response) {
    console.log((new Date()) + ' Received request for ' + request.url);
    response.writeHead(404);
    response.end();
});
server.listen(8080, function() {
    console.log((new Date()) + ' Server is listening on port 8080');
});

wsServer = new WebSocketServer({
    httpServer: server,
    autoAcceptConnections: false
});

function originIsAllowed(origin) {
  return true;
}

wsServer.on('request', function(request) {
    if (!originIsAllowed(request.origin)) {
      request.reject();
      console.log((new Date()) + ' Connection from origin ' + request.origin + ' rejected.');
      return;
    }
    
    var connection = request.accept('echo-protocol', request.origin);
    console.log((new Date()) + ' Connection accepted.');
    connection.on('message', function(message) {
        if (message.type === 'utf8') {
            console.log('Received Message: ' + message.utf8Data);
            connection.sendUTF(message.utf8Data);
        }
        else if (message.type === 'binary') {
            console.log('Received Binary Message of ' + message.binaryData.length + ' bytes');
            connection.sendBytes(message.binaryData);
        }
    });
    connection.on('close', function(reasonCode, description) {
        console.log((new Date()) + ' Peer ' + connection.remoteAddress + ' disconnected.');
    });
});

然后编写客户端文件index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>webSocket学习</title>
    <script>

var client = new WebSocket('ws://localhost:8080/', 'echo-protocol');
client.onerror = function() {
    console.log('Connection Error');
};

client.onopen = function() {
    console.log('WebSocket Client Connected');
    var contentd = document.getElementById('content');
    const p = document.createElement('p');
    p.innerHTML = `帅哥已上线`;
    contentd.appendChild(p);
};

client.onclose = function() {
    console.log('echo-protocol Client Closed');
};

client.onmessage = function(e) {
    var contentd = document.getElementById('content');
    if (typeof e.data === 'string') {
        const newDate =JSON.parse(e.data)
        const p = document.createElement('p');
        p.innerHTML = newDate.user  + "说:" +newDate.sendVal
        contentd.appendChild(p)
    }
};

function send(){
    var User = document.getElementById('User').value;
    var sendVal = document.getElementById('sendVal').value;
    const data = {
        "user":User,
        'sendVal':sendVal
    }
    sendVal && User ?function(){client.send(JSON.stringify(data));document.getElementById('sendVal').value='';}():alert("所有数据都不能为空")
   
}
</script>
</head>
<body>
    <label for="User">用户名:</label> <input type="text" id="User"><br>
    <label for="sendVal">消息 :</label> <input type="text" id="sendVal">
    <button onclick="send()">发送</button>
    <div id="content">

    </div>
</body>
</html>

编写完成以后,保存两个文件,在文件所在目录下打开控制台输入

node socketserver.js

在网页上就能进行尝试了,如图


image.png

点击发送:


image.png
本次尝试的直是单页面的,下次尝试多页面的通信,做成一个仿聊天室的再见。如有不对,欢迎指正

相关文章

  • websocket初探学习分享

    本文主要是使用的心得,参考的网址是websocket,本例中使用的是Websocket-Node 服务器模式,本地...

  • 2020-04-03

    ## webSocket初探 ## 目录 - 为什么WebSocket - 什么是WebSocket - WebS...

  • websocket初探

    Websocket 是什么? WebSocket协议是基于TCP的一种新的网络协议。它实现了浏览器与服务器全双工(...

  • websocket初探

    今天是想分享一下关于websocket在nodejs里面的相关实践。 websocket相关的知识大家在搜索引擎上...

  • Websocket初探

    Websocket是一种在单个TCP连接上进行全双工通信的网络协议,是HTML5新增的协议。那么为何要使用Webs...

  • webSocket初探

    一、WebSocket介绍与原理 WebSocket protocol 是HTML5一种新的协议。它实现了浏览器与...

  • 初探和实现websocket心跳重连

    初探和实现websocket心跳重连 心跳重连缘由 在使用websocket过程中,可能会出现网络断开的情况,比如...

  • WebSocket 初探(一)

    WebSocket WebSocket protocol 是HTML5一种新的协议。它实现了浏览器与服务器全双工通...

  • WebSocket 协议初探

    前言 公司项目使用WebSocket作为主要的请求方式,知其然也要知其所以然,会用也需要知道它的基本原理,所以写此...

  • 好程序员web前端培训分享WebSocket协议

    好程序员web前端培训分享WebSocket协议,WebSocket协议简介 一.WebSocket协议简介 1....

网友评论

      本文标题:websocket初探学习分享

      本文链接:https://www.haomeiwen.com/subject/tqrsvqtx.html