zoukankan      html  css  js  c++  java
  • IM即使聊天初探--基于 swoole websocket 实现

    仅为IM练习demo

    php 文件

    <?php
    
    $user = [];
    
    $server = new SwooleWebSocketServer("127.0.0.1", 9501);
    
    $server->on('open', function (SwooleWebSocketServer $server, $request) {
        echo "新用户 fd{$request->fd}
    ";
    	global $user;
    	$user[$request->fd]['id'] = $request->fd;
        $user[$request->fd]['name'] = "匿名用户".mt_rand(1000,9999);
        var_export($user);
    });
    
    $server->on('message', function (SwooleWebSocketServer $server, $frame) {
        echo "接收用户 {$frame->fd} 消息:{$frame->data}, opcode:{$frame->opcode},fin:{$frame->finish}
    ";
        // 循环发给用户
        global $user;
       	$msg = $user[(int)$frame->fd]['name'] . ': '. $frame->data;
       	var_dump($server->connections);
        // $server->connections 遍历所有websocket连接用户的fd,给所有用户推送
        foreach ($server->connections as $fd) {
            // 需要先判断是否是正确的websocket连接,否则有可能会push失败
            if ($server->isEstablished($fd)) {
                $server->push($fd, $msg);
            }
        }
        
    });
    
    $server->on('close', function ($ser, $fd) {
        echo "client {$fd} 下线
    ";
        global $user;
        unset($user[$fd]);
    });
    
    $server->start();
    

    前端页面

    <!DOCTYPE html>
    <html lang="en">
    <head>
    	<meta charset="UTF-8">
    	<title>IM DEMO BY JIHAN</title>
    	<style>
    		body {
    			 100%
    		}
    		h2 {
    			text-align: center;
    			margin: auto 0px
    		}
    		#main {
    			text-align: center;
    		}
    		#main div textarea{
    			margin: 0px auto;
    			display: block;
    		}
    		#content_show {
    			margin: 0px auto;
    			 60%;
    			border: 1px solid black;
    			height: 400px;
    			margin: auto 0px;
    			display: inline-block;
    		}
    		#footer {
    			text-align: center;
    		}
    		#footer input{
    			 200px;
    		}
    	</style>
    </head>
    <body>
    	<h2>聊天广场</h2>
    	<div id='main' >
    		<div id="content_show" >
    		</div>
    		<div id="footer">	
    			<input type="text" id="input">
    			<button type="submit" id="btn" onclick="handleClick()" >提交</button>
    		</div>
    	</div>
    	<script>
    		// 创建webSocket 链接
    		const url = 'ws://localhost:9501'
    		const socket = new WebSocket(url);
    
    		let content = document.querySelector('#content_show');
    
    		// 链接
    		socket.onopen = function(event) {
    			console.log('WebSocket is open now.', event)
    		}
    
    		// 消息
    		socket.onmessage = function(event) {
    			console.log('WebSocket message received:', event)
    			console.log('data:', event.data)
    			content.innerHTML += event.data + '<br/>'
    		}
    
    		// 错误
    		socket.onerror = function(event) {
    			console.log('WebSocket is error now.', event)
    		}
    
    		//关闭
    		socket.onclose = function(event) {
    			console.log('WebSocket is close now.')
    		}
    
    
    		function handleClick() {
    			console.log('点击提交')
    			let text = document.querySelector('input').value
    			socket.send(text)
    		}
    
    	</script>
    </body>
    </html>
    

    效果

  • 相关阅读:
    C# 保存base64格式图片
    C# 日期比较
    Socket的使用
    地质演变完整事记
    计算机实用的使用技巧
    ebook 电子书项目
    ppt演讲者模式
    IT行业三大定律
    史前生命
    Oracle DataGuard发生归档丢失增量备份恢复备库
  • 原文地址:https://www.cnblogs.com/smallyi/p/13875253.html
Copyright © 2011-2022 走看看