1、先下载weapp.socket.io.js, 下载地址https://down.bfw.wiki/file/16133523860652130077.html
2、将weapp.socket.io.js放到微信小程序的目录下
const io = require('../../weapp.socket.io.js')
const socket = io('ws://ip或域名:端口')
Page({
data: {
logs: []
},
onLoad: function () {
socket.on('connect', () => {
console.log('connection created.')
});
socket.on('new message', d => {
const {
username,
message
} = d;
console.log('received: ', username, message)
});
socket.emit('add user', "Jack");
socket.emit('new message', "Jack");
}
})
好了,我们再试试后端代码怎么写?后端我们是workman来实现,具体代码如下:
<?php
use Workerman\Worker;
use Workerman\WebServer;
use Workerman\Autoloader;
use PHPSocketIO\SocketIO;
// composer autoload
require_once '/data/server/phpsocket/vendor/autoload.php';
$io = new SocketIO(9097);
$io->on('connection', function($socket){
$socket->addedUser = false;
$socket->emit('new message', array(
'username'=> "tet",
'message'=> "dddd"
));
// when the client emits 'new message', this listens and executes
$socket->on('new message', function ($data)use($socket){
// we tell the client to execute 'new message'
$socket->broadcast->emit('new message', array(
'username'=> $socket->username,
'message'=> $data
));
});
// when the client emits 'add user', this listens and executes
$socket->on('add user', function ($username) use($socket){
global $usernames, $numUsers;
// we store the username in the socket session for this client
$socket->username = $username;
// add the client's username to the global list
$usernames[$username] = $username;
++$numUsers;
$socket->addedUser = true;
$socket->emit('login', array(
'numUsers' => $numUsers
));
// echo globally (all clients) that a person has connected
$socket->broadcast->emit('user joined', array(
'username' => $socket->username,
'numUsers' => $numUsers
));
});
// when the client emits 'typing', we broadcast it to others
$socket->on('typing', function () use($socket) {
$socket->broadcast->emit('typing', array(
'username' => $socket->username
));
});
// when the client emits 'stop typing', we broadcast it to others
$socket->on('stop typing', function () use($socket) {
$socket->broadcast->emit('stop typing', array(
'username' => $socket->username
));
});
// when the user disconnects.. perform this
$socket->on('disconnect', function () use($socket) {
global $usernames, $numUsers;
// remove the username from global usernames list
if($socket->addedUser) {
unset($usernames[$socket->username]);
--$numUsers;
// echo globally that this client has left
$socket->broadcast->emit('user left', array(
'username' => $socket->username,
'numUsers' => $numUsers
));
}
});
});
if (!defined('GLOBAL_START')) {
Worker::runAll();
}
网友回复