uniapp即时通讯、用socket.io-client的坑

uniapp即时通讯

历时一个月,高仿聊天APP雏形基本已完成,前端采用uni纯nvue混合开发,采用socket.io-client通讯协议来进行通讯,历史数据存储在手机、会话数据存在数据库。

import io from 'socket.io-client';
 
export default class Main extends Component {
    
    
    constructor(props) {
    
    
        super(props);
        this.state = {
    
    
            news: []
        };
    };
 
    getNews() {
    
    
 
        //和后端服务建立链接
        const socket = io('ws://10.0.3.69:8442');
 
        //监听后端推送过来的数据(注,init是可以自定义的,只要和后端约定好可行了!!)
        socket.on('init', (data) => {
    
    
 
            console.log(data); //这是后端推送过来的数据
 
            this.setState({
    
    
                news: data
            });
        });

        let msg = '我是前端向后端发送的数据!!';
 
        //向后端发送数据
        socket.emit('send', {
    
     text: msg});
        
        //后端在接收时也就是监听send就可以得到前端传过来的数据了
 
    };
    componentWillMount() {
    
    
        this.getNews();
    };
 
    componentDidMount() {
    
        
 
    };
 
    render() {
    
    
        return (
            <section className="main">
                <ul className="news-box">
                    <li>
                        {
    
    
                            this.state.news.map((item, index) =>{
    
    
                                return (`<b>${
     
     item.num}</b> <span>${
     
     item.content}</span>`)
                            })
                        }
                    </li>
                </ul>
               
            </section>
        );
    };
};
socket.on()方法:
    - socket.on()用于监听获取服务端(后端)发送过来的数据

    - socket.on('monitorName', callBack)有两个参数:

        + monitorName:是监听的标识,是自定义的,只要和后端约定好可行了!!)

        + callBack:是一个回调函数,里面的参数就是后端发送过来的数据
socket.emit()方法:
    - socket.emit()用于向服务端(后端)发送数据

    - socket.emit('monitorName', sendData)有两个参数:

        + monitorName:是监听的标识,是自定义的,只要和后端约定好可行了!!)

        + sendData:可以是字符串,也可以是{
    
    }JSON对象,这是向后端发送过去的数据

下面是一些功能截图
请添加图片描述

请添加图片描述

猜你喜欢

转载自blog.csdn.net/weixin_45361998/article/details/123147394