技术栈

服务端:

koa、koa-route、koa-websocket、request。

客户端:

html、css、js、websocket。

远程聊天API:

http://api.qingyunke.com/api.php?key=free&appid=0&msg=msg。

客户端展示

开发步骤

1.在桌面创建bbs文件夹,然后在文件夹内打开cmd,输入:

$ npm init

初始化箱项目,生成package.json包管理文件

2.cmd输入:

$ npm install koa --save

安装koa。

3.cmd输入:

$ npm install koa-route --save

安装koa路由模块。

4.cmd输入:

$ npm install koa-websocket --save

安装koawebsocket模块。

我的package.json:

{
"name": "bbs",
"version": "1.0.0",
"description": "",
"main": "server.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node server.js"
},
"author": "",
"license": "ISC",
"dependencies": {
"koa": "^2.8.1",
"koa-route": "^3.2.0",
"koa-websocket": "^6.0.0"
}
}

5.在bbs文件夹中新建server.js,项目启动入口文件。

添加内容如下:

const Koa = require('koa'),
route = require('koa-route'),
websockify = require('koa-websocket'),
http = require('http'),
app = websockify(new Koa()); app.ws.use(route.all('/', ctx => {
// websocket作为“ctx.websocket”添加到上下文中。
ctx.websocket.on('message', message => {
startRequest(message, ctx);
});
})); function startRequest(message, ctx) {
// 采用http模块向服务器发起一次get请求
http.get(`http://api.qingyunke.com/api.php?key=free&appid=0&msg=${encodeURI(message)}`, res => {
// 防止中文乱码
res.setEncoding('utf-8');
// 监听data事件,每次取一块数据
res.on('data', chunk => {
ctx.websocket.send(JSON.parse(chunk).content);
});
}).on('error', err => {
ctx.websocket.send('对不起,网络故障了');
});} // 监听端口、启动程序
app.listen(3000, err => {
if (err) throw err;
console.log('websocket服务器启动在3000端口');
})

假如对server.js还不清楚的,可以留言或者邮件咨询我。

6.在bbs文件夹中新建index.html文件,作为客户端展示文件。

添加内容如下:

<!DOCTYPE html>
<html lang="en"> <head>
<meta charset="UTF-8">
<title>实时聊天室</title>
<link rel="stylesheet" type="text/css" href="index.css">
</head> <body>
<div class="box">
<div class="title">实时聊天室</div>
<div class="input-box">
<input class="input" placeholder="你想说什么..." type="text" id="pl" onkeydown="keyEnter()" />
<div class="send" id="submit">发送</div>
</div>
<div class="view" id="ulView">
<ul id="view"></ul>
</div>
</div>
<script src="index.js"></script>
</body> </html>

7.在bbs文件夹中新建index.css,客户端的样式。

内容如下:

* {
padding:;
margin:;
-webkit-user-select: none;
-moz-user-select: none;
} html,
body {
height: 100%;
width: 100%;
background-color: #333;
position: relative;
font-size: 12px;
} .box {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background-color: #eee;
width: 320px;
height: 564px;
box-sizing: border-box;
} .title {
height: 40px;
line-height: 40px;
text-align: center;
background-color: #000;
color: #fff;
position: relative;
font-size: 16px;
} .input-box {
margin-top: 10px;
position: absolute;
bottom:;
background-color: #fff;
width: 100%;
height: 40px;
line-height: 32px;
padding: 4px;
padding-right:;
box-sizing: border-box;
display: -webkit-flex;
display: -moz-flex;
display: -ms-flex;
display: -o-flex;
display: flex;
-ms-align-items: center;
align-items: center;
justify-content: space-between;
border-top: 1px solid #eee;
} .input {
vertical-align: top;
height: 32px;
line-height: 32px;
outline: none;
border: 1px solid #ccc;
padding: 0 4px;
box-sizing: border-box;
flex:;
background-color: #eee;
border-radius: 4px;
margin-right: 10px;
margin-left: 4px;
} .input:focus {
border: 1px solid #ccc;
} .send {
width: 80px;
text-align: center;
height: 32px;
line-height: 32px;
cursor: pointer;
background-color: green;
color: #fff;
margin-right: 10px;
font-size: 14px;
} .send:active {
opacity: 0.6;
} li {
list-style: none;
padding: 6px 10px;
box-sizing: border-box;
} .my-say {
text-align: right;
} .say {
display: inline-block;
background-color: #fff;
font-size: 12px;
padding: 6px 4px;
border-radius: 4px;
margin-top: 1px;
vertical-align: top;
max-width: 220px;
} .computer-say .sayman {
background-color: #40E0D0;
} .my-say .sayman {
background-color: #FFA500;
} .my-say .say {
text-align: left;
} .sayman {
font-size: 10px;
display: inline-block;
height: 30px;
width: 30px;
background-color: #ccc;
border-radius: 50%;
text-align: center;
line-height: 30px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
padding: 0 4px;
box-sizing: border-box;
margin: 0 4px;
color: #fff;
} .view {
position: absolute;
top: 40px;
bottom: 40px;
left:;
width: 100%;
padding: 10px 0;
box-sizing: border-box;
overflow-y: auto;
}

8.在bbs文件夹中创建index.js文件,作为客户端js处理文件。

内容如下:

let submit = document.getElementById("submit"),
pl = document.getElementById("pl");
// 很重要 必须写,判断浏览器是否支持websocket
let CreateWebSocket = (() => {
return (urlValue) => {
if (window.WebSocket) return new WebSocket(urlValue);
if (window.MozWebSocket) return new MozWebSocket(urlValue);
return false;
}
})()
// 实例化websoscket websocket有两种协议ws(不加密)和wss(加密)
let webSocket = CreateWebSocket(`ws://127.0.0.1:3000`);
webSocket.onopen = evt => {
addMsg(1, '你好,欢迎进入实时聊天室!')
}
webSocket.onmessage = evt => {
// 这是服务端返回的数据
addMsg(1, evt.data);
submit.innerHTML = '发送';
}
// input事件发送数据
submit.onclick = (e) => {
if (e.target.innerHTML == '回复中...') {
return false
}
e.target.innerHTML = '回复中...';
const str = document.getElementById("pl").value;
webSocket.send(str);
addMsg(2, str);
}
// 绑定回车事件
function keyEnter() {
if (event.keyCode == 13) {
document.getElementById("submit").click();
}
}
// 添加消息
function addMsg(type, msg) {
let li = document.createElement('li');
// 1机器人/2自己
if (type == 1) {
li.classList.add('computer-say');
li.innerHTML = `<span class="sayman">机器人</span><span class="computer say">${msg}</span>`;
} else {
li.classList.add('my-say');
li.innerHTML = `<span class="computer say">${msg}</span><span class="sayman">我</span>`;
pl.value = '';
}
document.getElementById('view').appendChild(li);
document.getElementById('ulView').scrollTo(0, document.getElementById('view').clientHeight);
}

为了保证服务端包都可以加载进来,可以在bbs文件夹中打开cmd,然后输入:

$ npm install

到这里,程序就已经搭建完成了。

启动程序:

cmd输入:

$ node server.js

这样服务端就已经启动成功了。

直接右键浏览器打开index.html即可愉快地和机器人妹妹聊天了,告别单身狗了....

喜欢的麻烦点赞,谢谢

可以关注下本人博客,本人会坚持时不时更新好的博客给大家哦。

nodejs实现聊天机器人的更多相关文章

  1. 使用Botkit和Rasa NLU构建智能聊天机器人

    欢迎大家前往云+社区,获取更多腾讯海量技术实践干货哦~ 我们每天都会听到关于有能力涉及旅游.社交.法律​​.支持.销售等领域的新型机器人推出的新闻.根据我最后一次查阅的数据,单单Facebook Me ...

  2. 为Facebook messenger平台开发聊天机器人

    介绍 在电子商务网上商店发明之前,我们总是有机会与销售代表或分销商在选择商品或服务时交谈.在进入数字世界后,这个领域变得沉默.这样对顾客方便吗?我认为不是.向销售代表或经销商询问他们想要的产品或服务是 ...

  3. 【翻译】用AIML实现的Python人工智能聊天机器人

    前言 用python的AIML包很容易就能写一个人工智能聊天机器人. AIML是Artificial Intelligence Markup Language的简写, 但它只是一个简单的XML. 下面 ...

  4. 3.C#面向对象基础聊天机器人

    基于控制台的简单版的聊天机器人,词库可以自己添加. 聊天机器人1.0版本 源码如下: using System; using System.Collections.Generic; using Sys ...

  5. Python 简易聊天机器人

    聊天机器人 | |-----MySql | |---module--"逻辑运算层" | | | |---ciku--"与词库交互" | | | |---dict ...

  6. 使用图灵机器人API实现聊天机器人

    使用图灵机器人的API需要先注册,获取key才行,这我就不说了,自己到http://www.tuling123.com/注册一个账号即可. 下面就是一个简单的python调用API实现聊天机器人的简易 ...

  7. AngularJS作出简单聊天机器人

    简单聊天机器人 很初级的对话框形式.以前做对话框使用js,今天尝试使用AngularJS做出来 这里直接使用自己写的JSON数据. <!DOCTYPE html> <html lan ...

  8. 用 AIML 开发人工智能聊天机器人

    借助 Python 的 AIML 包,我们很容易实现人工智能聊天机器人.AIML 指的是 Artificial Intelligence Markup Language (人工智能标记语言),它不过是 ...

  9. 笔记5:QQ群聊天机器人

    之前经常在别人群里看到有自动回复消息的机器人. 功能有好多,可以玩各种游戏.觉得还蛮有意思的.. 于是就去请教别人怎么弄得,但是他们都说得好复杂,好高大上,无非就是不想让别人弄 本人是个不会轻易放弃的 ...

随机推荐

  1. 使用appscan安全扫描问题以及解决办法

    最近在做安全扫描,把遇到的一些问题以及一些解决方法记录下,以备后用. 扫描软件: IBM Security AppScan Standard  规则: 17441 1. 已解密的登录请求 (高) - ...

  2. springboot启动慢解决方法

    jdk的配置文件中,使用securerandom.source设置了熵源: cat /usr/java/jdk1.8.0_121/jre/lib/security/java.security secu ...

  3. 随笔编号-04 AngularJS 相关小问题解决方案合集

    1  解决 Select选择框遍历时,出现一个空白选项: <select style="width: 20%;margin-left: 5px;height: 31px;" ...

  4. Sqoop数据迁移工具的使用

    文章作者:foochane  原文链接:https://foochane.cn/article/2019063001.html Sqoop数据迁移工具的使用 sqoop简单介绍 sqoop数据到HDF ...

  5. Dig命令使用大全(转自别人翻译),稍加整理

    Dig简介:   Dig是一个在类Unix命令行模式下查询DNS包括NS记录,A记录,MX记录等相关信息的工具.由于一直缺失Dig man page文档,本文就权当一个dig使用向导吧.   Dig的 ...

  6. CentOS 7下安装配置搭建jdk+tomcat+MariaDB环境

    1.JDK安装 注意:rpm与软件相关命令 相当于window下的软件助手 管理软件 步骤: 1)查看当前Linux系统是否已经安装java 输入 rpm -qa | grep java 2)卸载两个 ...

  7. [Python] Django框架入门3——深入视图

    说明: 本文主要深入了解视图(views.py),涉及路由配置.定义视图.Request对象.Response对象.状态保持等. 一.路由配置 1.配置位置(settings.py 的 ROOT_UR ...

  8. 用故事解析setTimeout和setInterval(内含js单线程和任务队列)

    区别: setTimeout(fn,t): 延迟调用,超过了时间就调用回调函数,返回一个id,使用clearTimeout(id)取消执行. 注意:取消了里面的回调函数就不执行了哦,而不是取消的时候就 ...

  9. javaScript 基础知识汇总(六)

    1.基本类型与对象的区别 基本类型:是原始类型的中的一种值. 在JavaScript中有6中基本类型:string number  boolean  symbol  null  undefined 对 ...

  10. vue实现对语言的切换,结合vue-il8n。

    1.安装vue-i18n: npm install vue-i18n 如果npm长时间无反应,或安装失败,可以换成淘宝镜像安装: cnpm install vue-i18n 2.在main.js中引用 ...