用 websocket 做聊天系统是非常合适的.
https://github.com/webcpp/mongols 是一个运行于 linux 系统之上的开源 c++ 库, 可轻松开启一个 websocket 服务器.
首先, build 一个 websocket 服务器.
- #include <mongols/ws_server.hpp>
- //websocket server
- int main(int,char**){
- int port=9090;
- const char* host="127.0.0.1";
- mongols::ws_server server(host,port);
- server.run();
- }
才几行, 这就成了吗? 没错! 不信你用 wsdump.py 测试下. 测了啊, 怎么一发送消息就关闭了连接? 这是因为该服务器只接受 json 字符串消息, 并且规定了几个必要 field. 否则只能接收消息, 一发送就将关闭连接:
gid, 默认 0
uid, 默认 0
gfilter, 默认空数组 [], 表示转发给任意 gid 用户, 非空则只发送给特定 gid 用户
ufilter, 默认空数组 [], 表示转发给任意 uid 用户, 非空则只发送给特定 uid 用户
其他 field 为开发者自己决定.
因此, 开发者只需在前端用 javascript 即可完成所有核心开发工作.
这里有演示地址和全部开源代码, 包括前端和后端:
https://github.com/webcpp/fusheng
集成富文本编辑器 quill, 可发图片, 代码, latex 数学公式, 纯文本当然没问题啦.
需要知道如何自定义图片上传的 quill 开发者, 也可了解下. 很简单的:
- var quill = new Quill('#editor-container', {
- modules: {
- formula: true,
- syntax: true,
- toolbar: '#toolbar-container'
- },
- placeholder: 'To be a good man! The best brower is Chrome.',
- theme: 'snow',
- });
- var toolbar = quill.getModule('toolbar');
- toolbar.addHandler('image', function (e) {
- document.getElementById('get_file').click();
- });
- $('#get_file').change(function () {
- var upload_form = $('#upload_form');
- var options = {
- url: '/upload',
- type: 'post',
- success: function (ret) {
- if (ret.err == 0) {
- var range = quill.getSelection();
- quill.insertEmbed(range.index, 'image', ret.upload_path);
- $('#get_file').val('');
- } else {
- toast.show({
- // 'error', 'warning', 'success'
- // 'white', 'blue'
- type: 'error',
- // toast message
- text: 'upload error',
- // default: 3000
- time: 3000 // 5 seconds
- });
- }
- },
- error: function () {
- toast.show({
- type: 'error', text: 'upload error or too big.', time: 3000
- });
- }
- }
- upload_form.ajaxSubmit(options);
- });
来源: https://www.cnblogs.com/hi-nginx/p/9361903.html