Netty服务器部署在Android设备上,接收来自PC客户端的Java Socket客户端发送的JSON数据

import io.netty.handler.codec.json.JsonObjectDecoder;

import io.netty.handler.codec.string.StringDecoder;

import io.netty.handler.codec.string.StringEncoder;

import io.netty.handler.logging.LogLevel;

import io.netty.handler.logging.LoggingHandler;

public class MainActivity extends AppCompatActivity {

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

new Thread(new Runnable() {

@Override

public void run() {

try {

new Server();

} catch (Exception e) {

e.printStackTrace();

}

}

}).start();

}

private class Server {

private final int SERVER_PORT = 9000;

public Server() throws Exception {

EventLoopGroup bossGroup = new NioEventLoopGroup();

EventLoopGroup workerGroup = new NioEventLoopGroup();

ServerBootstrap b = new ServerBootstrap();

b.group(bossGroup, workerGroup).option(ChannelOption.SO_KEEPALIVE, true).channel(NioServerSocketChannel.class)

.option(ChannelOption.SO_BACKLOG, 128).handler(new LoggingHandler(LogLevel.INFO))

.childHandler(new ChannelInitializer() {

@Override

public void initChannel(SocketChannel sc) throws Exception {

sc.pipeline().addLast(new JsonObjectDecoder());//JSon解码器。

sc.pipeline().addLast(new StringEncoder());// 发送字符串的编码器。

sc.pipeline().addLast(new StringDecoder());// 接收到字符串的解码器。

sc.pipeline().addLast(new MyChannelHandlerAdapter());

}

});

// 绑定端口,开始接收进来的连接。

ChannelFuture cf = b.bind(SERVER_PORT).sync();

// 等待服务器关闭Socket。

cf.channel().closeFuture().sync();

}

private class MyChannelHandlerAdapter extends ChannelHandlerAdapter {

private final Logger logger = Logger.getLogger(MyChannelHandlerAdapter.class.getName());

@Override

public void channelActive(ChannelHandlerContext ctx) throws Exception {

System.out.println(“连接激活”);

ctx.writeAndFlush(“hello,world!”); // 若没有StringEncoder,则发送不出去字符串。

System.out.println(“写入完成”);

}

@Override

public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

//ByteBuf buf = (ByteBuf) msg;

logger.info(msg.toString());

//System.out.println(buf.toString(CharsetUtil.UTF_8));

//logger.info(msg.toString());

}

@Override

public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {

logger.info(“channelReadComplete”);

}

@Override

public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {

logger.log(Level.WARNING, “发生错误,关闭链接。”, cause);

ctx.close();

}

}

}

}

运行在PC电脑上的客户端,不停的发送字符串数据(转换成byte字节)。

import java.io.DataOutputStream;

import java.net.Socket;

import java.sql.Date;

import java.text.DateFormat;

import java.text.SimpleDateFormat;

import com.google.gson.Gson;

public class Client {

public Client() throws Exception {

Socket socket = new Socket(“localhost”, 6000);

System.out.println(“连接建立:” + socket.toString());

DataOutputStream dos = new DataOutputStream(socket.getOutputStream());

Date date = new Date(System.currentTimeMillis());

DateFormat dateFormat = new SimpleDateFormat(“MM-dd,HH:ss:SSS”);

Message message = new Message();

Gson gson = new Gson();

System.out.println(“开始循环发一万次ping…”);

for (int i = 0; i < 10000; i++) {

date.setTime(System.currentTimeMillis());

message.time = dateFormat.format(date);

String jsonString = gson.toJson(message);

尾声

对于很多初中级Android工程师而言,想要提升技能,往往是自己摸索成长,不成体系的学习效果低效漫长且无助。 整理的这些架构技术希望对Android开发的朋友们有所参考以及少走弯路,本文的重点是你有没有收获与成长,其余的都不重要,希望读者们能谨记这一点。

最后想要拿高薪实现技术提升薪水得到质的飞跃。最快捷的方式,就是有人可以带着你一起分析,这样学习起来最为高效,所以为了大家能够顺利进阶中高级、架构师,我特地为大家准备了一套高手学习的源码和框架视频等精品Android架构师教程,保证你学了以后保证薪资上升一个台阶。

当你有了学习线路,学习哪些内容,也知道以后的路怎么走了,理论看多了总要实践的。

进阶学习视频

附上:我们之前因为秋招收集的二十套一二线互联网公司Android面试真题 (含BAT、小米、华为、美团、滴滴)和我自己整理Android复习笔记(包含Android基础知识点、Android扩展知识点、Android源码解析、设计模式汇总、Gradle知识点、常见算法题汇总。)


《Android学习笔记总结+移动架构视频+大厂面试真题+项目实战源码》点击传送门,即可获取!
** (含BAT、小米、华为、美团、滴滴)和我自己整理Android复习笔记(包含Android基础知识点、Android扩展知识点、Android源码解析、设计模式汇总、Gradle知识点、常见算法题汇总。)

[外链图片转存中…(img-nhrJMTTA-1715854326100)]
《Android学习笔记总结+移动架构视频+大厂面试真题+项目实战源码》点击传送门,即可获取!

  • 3
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个简单的 Netty Socket 服务器示例,可将消息分发给10000个客户端: ```java import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelOption; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioServerSocketChannel; public class NettyServer { private final int port; public NettyServer(int port) { this.port = port; } public void run() throws Exception { EventLoopGroup bossGroup = new NioEventLoopGroup(); EventLoopGroup workerGroup = new NioEventLoopGroup(); try { ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(new NettyServerHandler()); } }) .option(ChannelOption.SO_BACKLOG, 128) .childOption(ChannelOption.SO_KEEPALIVE, true); ChannelFuture f = b.bind(port).sync(); f.channel().closeFuture().sync(); } finally { workerGroup.shutdownGracefully(); bossGroup.shutdownGracefully(); } } public static void main(String[] args) throws Exception { int port = 8080; NettyServer server = new NettyServer(port); server.run(); } } ``` 在上面的示例中,我们创建了一个 `ServerBootstrap`,并将其绑定到指定的端口上。我们使用了两个 `EventLoopGroup`,一个用于处理连接请求,一个用于处理客户端请求。当客户端连接到服务器时,`NettyServerHandler` 类将被调用来处理客户端请求。 下面是 `NettyServerHandler` 的示例代码,它将接收到的消息广播给所有连接的客户端: ```java import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import io.netty.util.CharsetUtil; public class NettyServerHandler extends ChannelInboundHandlerAdapter { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { ByteBuf in = (ByteBuf) msg; String received = in.toString(CharsetUtil.UTF_8); System.out.println("Server received: " + received); // Broadcast the received message to all clients ctx.writeAndFlush(Unpooled.copiedBuffer(received, CharsetUtil.UTF_8)); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { cause.printStackTrace(); ctx.close(); } } ``` 在上面的示例中,当服务器接收客户端的消息时,它将使用 `ctx.writeAndFlush()` 方法将消息发送给所有连接的客户端。 使用上述示例代码可以很容易地实现一个 Netty Socket 服务器,可将消息分发给10000个客户端

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值