一个最简单的WebSocket hello world demo

举报
汪子熙 发表于 2022/01/22 20:46:48 2022/01/22
【摘要】 服务器端代码不超过42行:const WSServer = require("./server.js");var counter = 0;function createWebsocket() { var host = "127.0.0.1"; var port = "9999"; var wsServer = WSServer.startServer(host, port); co...

服务器端代码不超过42行:

const WSServer = require("./server.js");

var counter = 0;

function createWebsocket() {

  var host = "127.0.0.1";
  var port = "9999";

  var wsServer =  WSServer.startServer(host, port);
  console.log("WebSocket server listens to: " + host + ":" + port);
  wsServer.on('open', (data) => {
    console.log('WS Client has connected: ' + data);

    setInterval(function(){ 
      counter++;
      WSServer.broadcast("Jerry: " + counter );
     }, 3000);
    
  });

  wsServer.on('dataWS', (data) => {
    console.log('Receive Data from WebUI : ' +  data);
  });

  wsServer.on('disconnect', (data) => {
    console.log('WSServer disconnect:' + data.name);
  });

  wsServer.on('close', (data) => {
    console.log('WSServer close: ' + data.name);
  });

  wsServer.on('end', (data) => {
    console.log('WSServer Close: '+data.name);
  });

  wsServer.on('error', (data) => {
  });
}

createWebsocket();

代码第10行创建一个WebSocket服务器,监听在9999端口上:

第15~18行每隔3秒发送一个字符串到浏览器,用一个计数器标识每次发送的请求。

代码里所需的server.js我已经上传到我的Github上了:
https://github.com/i042416/KnowlegeRepository/blob/master/practice/nodejs/server.js

使用nodejs启动这个服务器:

网页端代码:

<html>
<script src="socket.io.dev.js">
</script>
<script>
console.log("1");

  var socket = io('ws://127.0.0.1:9999');
  socket.on('connect', function(){
    console.log("connected!");
  });
  socket.on('event', function(data){
    console.log("event: " + data);
  });

  socket.on('news', function(data){
    console.log("data from server: " + JSON.stringify(data,2,2));
  });

  socket.on('disconnect', function(){
    console.log("disconnect...");
  });

</script>
</html>

浏览器端每隔三秒收到服务器推送的消息,打印在console上:

首先通过下面的链接下载openSSL
https://slproweb.com/products/Win32OpenSSL.html

下载完毕后,执行openssl进入交互式界面:

使用命令生成privatekey.pem 1024意思是1024位长度。

openssl genrsa -out privatekey.pem 1024

生成的privatekey.pem,打开看一看长啥样:

什么是pem文件?

.pem - Defined in RFCs 1421 through 1424, this is a container format that may include just the public certificate (such as with Apache installs, and CA certificate files /etc/ssl/certs), or may include an entire certificate chain including public key, private key, and root certificates. Confusingly, it may also encode a CSR (e.g. as used here) as the PKCS10 format can be translated into PEM. The name is from Privacy Enhanced Mail (PEM), a failed method for secure email but the container format it used lives on, and is a base64 translation of the x509 ASN.1 keys.

简单的说,就是一个密钥文件。

第二步,基于第一步生成的密钥文件生成一个证书请求:
openssl req -new -key privatekey.pem -out certrequest.csr

如果懒得维护证书明细,直接敲回车,会自动填入默认值:

最后基于第一步生成的密钥和证书请求生成一个数字证书:当然颁发机构就是自己了,仅用于测试目的。
openssl x509 -req -in certrequest.csr -signkey privatekey.pem -out certificate.pem

至此我们有了privatekey.pem和Certificate.pem两个证书了。

下面是我https服务器的代码,很简单,只有50几行:

var app = require('express')();
var fs    = require('fs');
var https = require('https');

var httpOptions =  {
 key: fs.readFileSync("keys/privatekey.pem"),
 cert: fs.readFileSync("keys/certificate.pem")
}

var server = https.createServer(httpOptions, app);
var io = require('socket.io')(server);

console.log("https server listens on port 8080...");

server.listen(8080);

function print_env(){
  console.log(process.env);
}

app.get('/', function (req, res) {

  var response = "Hello World";
  res.send(response);
});

app.get('/env', function (req, res) {

  print_env();
  // res.sendFile(__dirname + '/index.html');
  var response = JSON.stringify(process.env);
  res.send(response);
});

app.get('/redis', function (req, res) {

  var redisClient = require("./redisClient");
  
  function callback(response){
    // var response = "ok";//JSON.stringify(process.env);
    res.send(response);
  }
  redisClient.test(callback);
});

io.on('connection', function (socket) {
  console.log("connect comming from client: " + socket.id);
  socket.emit('messages_jerry', { hello: 'world greeting from Server!' });
  socket.on('messages', function (data) {
    console.log("data received from Client:" + JSON.stringify(data,2,2));
  });
});

从代码里不难理解这两个pem文件是如何用在https服务器里的。
最后在浏览器里测试。因为是自己颁发的证书,没有经过CA验证,所以浏览器会显示一个警告。

【版权声明】本文为华为云社区用户原创内容,转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息, 否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。