小程序,巧应用(pdf+epub+mobi+txt+azw3)
7.3.3 程序细化
服务器端采用高性能、异步事件驱动的NIO框架Netty来实现,部分代码如下:
/***RobotsServer实现
***/
import java.net.InetSocketAddress;
import java.util.concurrent.Executors;
import org.jboss.netty.bootstrap.ServerBootstrap;
import org.jboss.netty.channel.ChannelFactory;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;
public class RobotsServer {
public static void main(String[] args){
ChannelFactory factory = new NioServerSocketChannelFactory(Executors.
newCachedThreadPool(),Executors.newCachedThreadPool());
ServerBootstrap bootstrap = new ServerBootstrap(factory);
bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
public ChannelPipeline getPipeline() throws Exception {
// 机器人进行语义分析,然后返回给客户
return Channels.pipeline(new RobotsServerHandler());
}
});
bootstrap.setOption("child.tcpNoDelay",true);
bootstrap.setOption("child.keepAlive",true);
bootstrap.bind(new InetSocketAddress(8080));
}
}
/***RobotsServerHandler实现
***/
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelHandler;
public class RobotsServerHandler extends SimpleChannelHandler {
@Override
public void messageReceived(ChannelHandlerContext ctx,MessageEvent e) throws
Exception {
Channel channel = e.getChannel();
Object retMessage = messageHandler(e.getMessage());
channel.write(retMessage);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx,MessageEvent e) throws
Exception {
e.getCause().printStackTrace();
e.getChannel().close();
}
private Object messageHandler(Object message){
// 可以进行一些自然语义分析,然后加上搜索,快速告诉客户你的答案
// 在这里我们只是简单返回,相当于
ECHO的作用
return message;
}"+e.detail.value.q)
console.log(e.detail)
this.setData({
text: initData + '\n' + extraLine.join('\n'),
tt: ''
})
},
wx.connectSocket({
url: 'ws:// www.apayado.com/RobotsServer',
data:{
},
header:{
'content-type': 'application/json'
},
method:"GET"
}),
wx.onSocketOpen(function(res) {
socketOpen = true
}),
打开websocket如下:
function sendSocketMessage(msg) {
if (socketOpen) {
wx.sendSocketMessage({
data:msg
})
} else {
console.log("还没有连接,不能发送:
"+msg)
}
},
发送msg信息给服务器:
wx.onSocketMessage(function(res) {
console.log('收到服务器内容:
' + res.data)
extraLine.push("高冷:
" + res.data)
this.setData({
text: initData + '\n' + extraLine.join('\n'),
tt: ''
})
})
在收到内容后,push到数组中保存extraLine数组在index.js头部定义:
var extraLine = [];
var socketOpen = false;
Page({
data: {
text: initData,
tt: ''
},
这个例子展示了如何使用WebSocket进行客户端和服务器间的通信,小程序在有了WebSocket之后,意味着可以自己实现TCP/UDP短连接、长连接,完成聊天、IM、股票、交易等实时交互的通信应用,甚至可以用于物联网等领域,非常灵活强大,发挥空间巨大。