IM即使聊天初探--基于 swoole websocket 实现

仅为IM练习demo

php 文件

<?php

$user = [];

$server = new Swoole\WebSocket\Server("127.0.0.1", 9501);

$server->on(‘open‘, function (Swoole\WebSocket\Server $server, $request) {
    echo "新用户 fd{$request->fd}\n";
	global $user;
	$user[$request->fd][‘id‘] = $request->fd;
    $user[$request->fd][‘name‘] = "匿名用户".mt_rand(1000,9999);
    var_export($user);
});

$server->on(‘message‘, function (Swoole\WebSocket\Server $server, $frame) {
    echo "接收用户 {$frame->fd} 消息:{$frame->data}, opcode:{$frame->opcode},fin:{$frame->finish}\n";
    // 循环发给用户
    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} 下线\n";
    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 {
			width: 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;
			width: 60%;
			border: 1px solid black;
			height: 400px;
			margin: auto 0px;
			display: inline-block;
		}
		#footer {
			text-align: center;
		}
		#footer input{
			width: 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>

效果
IM即使聊天初探--基于 swoole websocket 实现

IM即使聊天初探--基于 swoole websocket 实现

上一篇:数据下载网站记录


下一篇:ASP.NET Core Program.cs