用websocket做聊天系统是非常合适的。

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.否则只能接收消息,一发送就将关闭连接:

  1. gid,默认0
  2. uid,默认0
  3. gfilter,默认空数组[],表示转发给任意gid用户,非空则只发送给特定gid用户
  4. ufilter,默认空数组[],表示转发给任意uid用户,非空则只发送给特定uid用户

其他field为开发者自己决定。

因此,开发者只需在前端用javascript即可完成所有核心开发工作。

这里有演示地址和全部开源代码,包括前端和后端:

https://github.com/webcpp/fusheng

用mongols轻松打造websocket应用-LMLPHP

集成富文本编辑器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); });

  

05-11 15:05