• webSocket前端+nodejs后端


    一:下面是一个简单的案例,回车发送消息,多人在线聊天

    1.前端代码

    <!DOCTYPE html>
    <html>
    
    <head>
    	<meta charset="UTF-8">
    	<title>WebSocket Chat</title>
    </head>
    
    <body>
    	<script type="text/javascript">
    		var socket;
    		if (!window.WebSocket) {
    			window.WebSocket = window.MozWebSocket;
    		}
    		if (window.WebSocket) {
    			socket = new WebSocket("ws://10.22.12.12:8080/ws");
    			socket.onmessage = function (event) {
    				var ta = document.getElementById('responseText');
    				ta.value = ta.value + '
    ' + event.data
    			};
    			socket.onopen = function (event) {
    				var ta = document.getElementById('responseText');
    				ta.value = "连接开启!";
    			};
    			socket.onclose = function (event) {
    				var ta = document.getElementById('responseText');
    				ta.value = ta.value + "连接被关闭";
    			};
    		} else {
    			alert("你的浏览器不支持 WebSocket!");
    		}
    
    		function send(message) {
    			if (!window.WebSocket) {
    				return;
    			}
    			if (socket.readyState == WebSocket.OPEN) {
    				socket.send(message);
    			} else {
    				alert("连接没有开启.");
    			}
    		}
        document.onkeydown=function(event){
        var code = event.keyCode;
        if(code ==13){ //这是键盘的enter监听事件
            //绑定焦点,有可能不成功,需要多试试一些标签 
            document.getElementById("mySend").onclick();
            setTimeout(()=>{
              document.getElementById("myInput").value = ''
            },50)
        }
    }
    	</script>
    	<form onsubmit="return false;">
    		<h3>WebSocket 聊天室:</h3>
    		<textarea id="responseText" style=" 500px; height: 300px;"></textarea>
    		<br>
    		<input type="text" id="myInput" name="message" style=" 300px" value="Hello~~~">
    		<input type="button" id="mySend" value="发送消息" onclick="send(this.form.message.value)">
    		<input type="button" onclick="javascript:document.getElementById('responseText').value=''" 
    			value="清空聊天记录">
    	</form>
    	<br>
    </body>
    
    </html>
    

    2.后端代码

    const WebSocket = require('ws');
    
    const server = new WebSocket.Server({ port: 8080 });
    
    server.on('open', function open() {
      console.log('connected');
    });
    
    server.on('close', function close() {
      console.log('disconnected');
    });
    
    server.on('connection', function connection(ws, req) {
      const ip = req.connection.remoteAddress;
      const port = req.connection.remotePort;
      const clientName = ip + port;
    
      console.log('%s is connected', clientName)
    
      // 发送欢迎信息给客户端
      ws.send("Welcome " + clientName);
    
      ws.on('message', function incoming(message) {
        console.log('received: %s from %s', message, clientName);
        
        // 广播消息给所有客户端
        server.clients.forEach(function each(client) {
          if (client.readyState === WebSocket.OPEN) {
            client.send( clientName + " -> " + message);
          }
        });
    
      });
    
    });
    

    参考文章:https://waylau.com/node.js-websocket-chat/

  • 相关阅读:
    RVM Ruby 版本管理器的删除 Gatling
    JWT 构建Rails API 授权登录
    Linux grep根据关键字匹配前后几行
    bootstrap-table 常用总结-树形结构
    linux 下jq的使用
    SHELL脚本获取域名对应的IP地址
    golang将切片或数组进行分组
    linux的统计实现
    Linux:“awk”命令的妙用
    rails 上传文件
  • 原文地址:https://www.cnblogs.com/sugartang/p/13859632.html
Copyright © 2020-2023  润新知