当前位置:   article > 正文

JS案例:Socket聊天室(两种方式)_ws.onmessage另一种写法

ws.onmessage另一种写法

一.socket轮询(每隔一段时间向后端请求一次,增加服务器压力):

由于socket连接时采用ws/wss协议,页面必须放在服务器端,所以首先用node产生一个静态文件夹,方便通过IP直接访问

static.js:

  1. const express = require('express');//这里要引入express
  2. const app = express();
  3. const path = require('path');
  4. app.use('/main', express.static(path.join(__dirname, './html')));//设置静态文件夹
  5. app.listen(2048, () => {//端口号不能与socket监听的端口号一样
  6. console.log('static 2048 Server Start~');
  7. })

在html界面做一些简单的布局以及socket数据请求:

index.html:

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8" />
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  6. <meta http-equiv="X-UA-Compatible" content="ie=edge" />
  7. <title>Document</title>
  8. <style>
  9. #text {
  10. width: 350px;
  11. height: 30px;
  12. }
  13. #netName {
  14. width: 150px;
  15. height: 30px;
  16. }
  17. </style>
  18. </head>
  19. <body>
  20. <textarea name="" id="msg" cols="80" rows="30" readonly></textarea><br />
  21. <input id="netName" type="text" placeholder="名称" />
  22. <input id="text" type="text" placeholder="消息" />
  23. <button onclick="clickHandler()">发送</button>
  24. <script>
  25. setInterval(sendMsg, 1000); //这里做轮询请求
  26. function sendMsg(data) { //封装WebSocket请求函数
  27. if (!data) {
  28. data = {
  29. err: 1
  30. }; //根据参数判断是否符合数据规范
  31. }
  32. var ws = new WebSocket("ws://192.168.1.4:1024"); //使用ws协议对1024端口进行请求
  33. ws.onopen = function () {
  34. ws.send(JSON.stringify(data));
  35. };
  36. ws.onmessage = getData;
  37. }
  38. function getData(evt) { //将请求成功后返回的数据接收
  39. var received_msg = evt.data;
  40. var val = JSON.parse(evt.data).join("\n");
  41. msg.value = val;
  42. }
  43. document.addEventListener("keyup", e => { //回车键发送
  44. if (e.keyCode !== 13) return;
  45. clickHandler(e);
  46. });
  47. function clickHandler() { //点击Button时将数据发送到服务端
  48. if (netName.value.trim().length == 0 || text.value.trim().length == 0)
  49. return;
  50. var obj = {
  51. err: 0,
  52. netName: netName.value,
  53. msg: text.value
  54. };
  55. sendMsg(obj);
  56. text.value = ""; //每次发送后将内容制空
  57. }
  58. </script>
  59. </body>
  60. </html>

Client.js(客户端)

  1. const WebSocket = require('ws');//这里引入一个模块ws
  2. const ws = new WebSocket('ws://192.168.1.4:1024');//对1024端口进行监听
  3. ws.on('open', function() {
  4. console.log('Client is listening on port 1024');
  5. });
  6. ws.on('message', function(msg) {
  7. ws.send(msg);//获取到前端传来的数据后,直接向服务端传递
  8. });
  9. ws.on('close',function(){
  10. console.log('Client close')
  11. });

Server.js

  1. const static = require('./static')//引入刚刚创建的static静态目录
  2. const client = require('./client')//引入客户端
  3. const WebSocket = require('ws');
  4. let list = [];
  5. const wss = new WebSocket.Server({//对1024端口进行监听
  6. port: 1024
  7. }, () => {
  8. console.log('Server is listening on port 1024');
  9. });
  10. wss.on('connection', function (ws) {
  11. ws.on('message', function (msg) {//对数据过滤和处理
  12. if(!JSON.parse(msg).err){
  13. list.push(JSON.parse(msg).netName + ' 说: ' + JSON.parse(msg).msg)
  14. }
  15. ws.send(JSON.stringify(list));//将数据传到前端
  16. });
  17. });

二.socketio长链接(与轮询不同,使前后端通过事件处理机制时刻保持连接状态)

同样产生一个静态文件夹:

static.js:

  1. const express = require('express');
  2. const app = express();
  3. const path = require('path');
  4. app.use('/main', express.static(path.join(__dirname, './static')));
  5. app.listen(2048, () => {
  6. console.log('static 2048 Server Start~');
  7. })

index.html

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8" />
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  6. <meta http-equiv="X-UA-Compatible" content="ie=edge" />
  7. <title>Document</title>
  8. <style>
  9. #text {
  10. width: 350px;
  11. height: 30px;
  12. }
  13. #netName {
  14. width: 150px;
  15. height: 30px;
  16. }
  17. </style>
  18. <script src="./socket.io.js"></script>
  19. <!-- 首先用npm下载socketio并且使用socket.io-client中的socket.io.js -->
  20. </head>
  21. <body>
  22. <textarea name="" id="msg" cols="80" rows="30" readonly></textarea><br />
  23. <input id="netName" type="text" placeholder="名称" />
  24. <input id="text" type="text" placeholder="消息" />
  25. <button onclick="clickHandler()">发送</button>
  26. <script>
  27. var socket = io.connect('http://192.168.1.4:1024'); //建立http连接
  28. var list = [] //本地聊天记录缓存
  29. function clickHandler() {
  30. if (netName.value.trim().length == 0 || text.value.trim().length == 0)
  31. return; //过滤输入框
  32. var obj = {
  33. netName: netName.value,
  34. msg: text.value
  35. };
  36. list.push(obj.netName + ' 说: ' + obj.msg)
  37. socket.emit('send', obj)//触发send事件
  38. getData(list);
  39. text.value = "";
  40. }
  41. socket.on('msg', function (msg) {//添加msg监听事件
  42. list = msg;
  43. getData(list)
  44. })
  45. function getData(arr) {//将聊天记录放至area标签
  46. msg.value = arr.join('\n');
  47. }
  48. </script>
  49. </body>
  50. </html>

Server.js:

  1. const static = require("./static");//引入刚刚创建的static静态目录
  2. let list = [];//聊天记录缓存
  3. var express = require("express");
  4. var app = express();
  5. var server = require("http").Server(app);
  6. const io = require("socket.io")(server);
  7. io.on("connection", function(client) {
  8. client.on("send", data => {//添加send监听事件
  9. list.push(data.netName + " 说: " + data.msg);//将前端事件传过来的参数进行处理
  10. sendList(list, client);//将数据通过事件发送到前端
  11. });
  12. });
  13. function sendList(list, target) {
  14. target.broadcast.emit("msg", list);//触发msg事件
  15. }
  16. server.listen(1024, "192.168.1.4", () => {
  17. console.log("Connect Success At 1024");
  18. });

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/盐析白兔/article/detail/244062
推荐阅读
相关标签
  

闽ICP备14008679号