服务端实现大概思路
服务端需要创建socket端口供客户端(android)链接,为了能实现消息的转发,还需要记录一下长链接与用户的对应关系。总体大概思路是,服务端端口创建完成上线后,每次收到客户端的链接,则记录该链接和用户关系。收到客户端发来的消息后,识别接收方,然后从关系表中找到接收方所在的长链接,最后发送。
在框架上我选择了Netty,Netty 是一个基于NIO的客户、服务器端的编程框架,可以快速和简单的开发出一个网络应用,无疑是一强大的网络框架。我们目前就使用了它来实现长链接服务。
1、创建一个maven项目,pom引入netty
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.1.39.Final</version>
</dependency>
2、创建SocketServer类,用于创建长链接服务,在start()中,使用netty框架,创建服务。
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
public class SocktServer {
private static int port;
public SocktServer(int port) {
this.port = port;
}
public static void start() throws InterruptedException {
EventLoopGroup bossGroup = new NioEventLoopGroup();//主线程组
EventLoopGroup workerGroup = new NioEventLoopGroup();//从线程组
try {
ServerBootstrap serverBootstrap = new ServerBootstrap();
serverBootstrap.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.childHandler(new WebSocketinitializer());
ChannelFuture channelFuture = serverBootstrap.bind(port).sync();//启动服务
channelFuture.channel().closeFuture().sync();
} finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
}
3、创建WebSocketinitializer类,这工具类参考了网上大佬们的代码,相关逻辑注释里解释的很清楚。
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
public class WebSocketinitializer extends ChannelInitializer<SocketChannel> {
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
//从Channel中获取对应的pipeline
ChannelPipeline channelPipeline = socketChannel.pipeline();
//添加相应的助手类与处理器
/**
* WebSokect基于Http,所以要有相应的Http编解码器,HttpServerCodec()
*/
channelPipeline.addLast(new HttpServerCodec());
//在Http中有一些数据流的传输,那么数据流有大有小,如果说有一些相应的大数据流处理的话,需要在此添加
//ChunkedWriteHandler:为一些大数据流添加支持
channelPipeline.addLast(new ChunkedWriteHandler());
//UdineHttpMessage进行处理,也就是会用到request以及response
//HttpObjectAggregator:聚合器,聚合了FullHTTPRequest、FullHTTPResponse。。。,当你不想去管一些HttpMessage的时候,直接把这个handler丢到管道中,让Netty自行处理即可
channelPipeline.addLast(new HttpObjectAggregator(2048*64));
// /ws:一开始建立连接的时候会使用到,可自定义
//WebSocketServerProtocolHandler:给客户端指定访问的路由(/ws),是服务器端处理的协议,当前的处理器处理一些繁重的复杂的东西,运行在一个WebSocket服务端
//另外也会管理一些握手的动作:handshaking(close,ping,pong) ping + pong = 心跳,对于WebSocket来讲,是以frames进行传输的,不同的数据类型对应的frames也不同
channelPipeline.addLast(new WebSocketServerProtocolHandler("/ws"));
//添加自动handler,读取客户端消息并进行处理,处理完毕之后将相应信息传输给对应客户端
channelPipeline.addLast(new ChatHandler());
}
}
4、创建ChatHandler类,实现业务逻辑处理。创建用户和ChannelHandlerContext长链接关系的hashmap,用于记录用户和长链接的绑定关系。在用户挂载长链接,第一次发出消息时,识别用户id,然后记录在hashmap中。在长链接断掉时删掉hashmap的键值,实现关系绑定维护。
我在这里自定义了用户名规则,user_id为String类型,u开头,比如u_00001,u_00002这样。所以代码如下:
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.concurrent.GlobalEventExecutor;
public class ChatHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
public static HashMap<ChannelHandlerContext,String> client=new HashMap<String, ChannelHandlerContext>();
@Override
public void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
System.out.println(msg.text());
if(msg.text().substring(0,1).equals("u")){ //判断传来是不是u开头,是则认为发送的为用户名
client.put(ctx,msg.text());//绑定上线用户user_id和ctx
System.out.println(msg.text()+" u_*** "+client.size());
}else {
System.out.println("收到消息"+msg.text());
}
}
//客户端连接
@Override
public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
}
//客户端断开
@Override
public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
client.remove(ctx)
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable e) throws Exception {
e.printStackTrace();
}
//给指定链接发消息
public void SendMessage(ChannelHandlerContext ctx String message) {
ctx.channel().writeAndFlush(new TextWebSocketFrame(message));
}
}
5、由于在判断用户的时候,采用了非常粗暴的方式,直接判断信息内容是否为字母 u 开头,然后保存用户关系。所以此地方需要Android端对应的一段逻辑:在用户每次连上长链接后,发送的第一条消息是自己的user_id。
//Android部分代码
String user_id="u_00001";
//将上次客户端的连接client.connectBlocking(),封装到connect()方法中
private void connect () {
new Thread() {
@Override
public void run() {
KLog.i("开始连接socket");
try {
client.connectBlocking(); //连接socket
if (client.isOpen()) {
client.send(user_id); //发送消息
}
} catch (InterruptedException e) {
e.printStackTrace();
KLog.e("socket连接发送失败: "+e);
}
}
}.start();
}
6、最后在项目main方法中,调用SocketServer的start方法,启动服务。我这里端口用的9091,只要不与本地端口占用冲突,大家自己随便选即可。
public static void main(String[] args) {
try {
System.out.println("http://127.0.0.1:9091/ws");
new SocktServer(9091).start();
}catch(Exception e) {
System.out.println(e);
}
}
7、回到Android端的代码,结合上一篇的代码,所以连接socket的部分应为
import java.net.URI;
//Android部分代码
String url="ws://127.0.0.1:9091/ws"
URI uri = URI.create(url);
WsClient client = new WsClient(uri){
@Override
public void onMessage(String message) {
\\在这里处理服务端发来的消息
KLog.d("onMessage", message);
}
@Override
public void onOpen(ServerHandshake handshakedata) {
super.onOpen(handshakedata);
KLog.i("SocketClientService", "websocket连接成功");
}
@Override
public void onClose(int code, String reason, boolean remote) {
KLog.i("SocketClient", "onClose()");
}
}
connect();
这样大家就可以完成连接,并发送消息了