java tcp粘包_socket拆包与组班

java tcp粘包_socket拆包与组班importjava.nio.ByteBuffer;importio.netty.bootstrap.ServerBootstrap;importio.netty.buffer.ByteBuf;importio.netty.buffer.Unpooled;importio.netty.channel.ChannelFuture;importio.netty.channel.Channe…

大家好,又见面了,我是你们的朋友全栈君。如果您正在找激活码,请点击查看最新教程,关注关注公众号 “全栈程序员社区” 获取激活教程,可能之前旧版本教程已经失效.最新Idea2022.1教程亲测有效,一键激活。

Jetbrains全系列IDE使用 1年只要46元 售后保障 童叟无欺

44ff9330108307659dcbcb3cbe1f3c8c.png

f81aacb62919f94e4faffda868e5c64f.png

import java.nio.ByteBuffer;

import io.netty.bootstrap.ServerBootstrap;

import io.netty.buffer.ByteBuf;

import io.netty.buffer.Unpooled;

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;

import io.netty.handler.codec.DelimiterBasedFrameDecoder;

import io.netty.handler.codec.FixedLengthFrameDecoder;

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

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

public class Server {

public static void main(String[] args) throws Exception{

//1 创建2个线程,一个是负责接收客户端的连接。一个是负责进行数据传输的

EventLoopGroup pGroup = new NioEventLoopGroup();

EventLoopGroup cGroup = new NioEventLoopGroup();

//2 创建服务器辅助类

ServerBootstrap b = new ServerBootstrap();

b.group(pGroup, cGroup)

.channel(NioServerSocketChannel.class)

.option(ChannelOption.SO_BACKLOG, 1024)

.option(ChannelOption.SO_SNDBUF, 32*1024)

.option(ChannelOption.SO_RCVBUF, 32*1024)

.childHandler(new ChannelInitializer() {

@Override

protected void initChannel(SocketChannel sc) throws Exception {

//设置特殊分隔符

ByteBuf buf = Unpooled.copiedBuffer(“$_”.getBytes());

sc.pipeline().addLast(new DelimiterBasedFrameDecoder(1024, buf));

//设置字符串形式的解码

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

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

}

});

//4 绑定连接

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

//等待服务器监听端口关闭

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

pGroup.shutdownGracefully();

cGroup.shutdownGracefully();

}

}

import io.netty.bootstrap.Bootstrap;

import io.netty.buffer.ByteBuf;

import io.netty.buffer.Unpooled;

import io.netty.channel.ChannelFuture;

import io.netty.channel.ChannelInitializer;

import io.netty.channel.EventLoopGroup;

import io.netty.channel.nio.NioEventLoopGroup;

import io.netty.channel.socket.SocketChannel;

import io.netty.channel.socket.nio.NioSocketChannel;

import io.netty.handler.codec.DelimiterBasedFrameDecoder;

import io.netty.handler.codec.FixedLengthFrameDecoder;

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

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

public class Client {

public static void main(String[] args) throws Exception {

EventLoopGroup group = new NioEventLoopGroup();

Bootstrap b = new Bootstrap();

b.group(group)

.channel(NioSocketChannel.class)

.handler(new ChannelInitializer() {

@Override

protected void initChannel(SocketChannel sc) throws Exception {

//

ByteBuf buf = Unpooled.copiedBuffer(“$_”.getBytes());

sc.pipeline().addLast(new DelimiterBasedFrameDecoder(1024, buf));

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

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

}

});

ChannelFuture cf = b.connect(“127.0.0.1”, 8765).sync();

cf.channel().writeAndFlush(Unpooled.wrappedBuffer(“bbbb$_”.getBytes()));

cf.channel().writeAndFlush(Unpooled.wrappedBuffer(“cccc$_”.getBytes()));

//等待客户端端口关闭

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

group.shutdownGracefully();

}

}

import io.netty.buffer.Unpooled;

import io.netty.channel.ChannelHandlerAdapter;

import io.netty.channel.ChannelHandlerContext;

public class ServerHandler extends ChannelHandlerAdapter {

@Override

public void channelActive(ChannelHandlerContext ctx) throws Exception {

System.out.println(” server channel active… “);

}

@Override

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

String request = (String)msg;

System.out.println(“Server :” + msg);

String response = “服务器响应:” + msg + “$_”;

ctx.writeAndFlush(Unpooled.copiedBuffer(response.getBytes()));

}

@Override

public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {

}

@Override

public void exceptionCaught(ChannelHandlerContext ctx, Throwable t) throws Exception {

ctx.close();

}

}

import io.netty.channel.ChannelHandlerAdapter;

import io.netty.channel.ChannelHandlerContext;

import io.netty.util.ReferenceCountUtil;

public class ClientHandler extends ChannelHandlerAdapter{

@Override

public void channelActive(ChannelHandlerContext ctx) throws Exception {

System.out.println(“client channel active… “);

}

@Override

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

try {

String response = (String)msg;

System.out.println(“Client: ” + response);

} finally {

ReferenceCountUtil.release(msg);

}

}

@Override

public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {

}

@Override

public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {

ctx.close();

}

}

4c2bb1f0b41aeeb90abf3bd93e911554.png

import io.netty.bootstrap.ServerBootstrap;

import io.netty.channel.ChannelFuture;

import io.netty.channel.ChannelHandler;

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;

import io.netty.handler.logging.LogLevel;

import io.netty.handler.logging.LoggingHandler;

import io.netty.handler.timeout.ReadTimeoutHandler;

public class Server {

public Server() {

}

public static void main(String[] args) throws Exception {

EventLoopGroup pGroup = new NioEventLoopGroup();

EventLoopGroup cGroup = new NioEventLoopGroup();

ServerBootstrap b = new ServerBootstrap();

((ServerBootstrap)((ServerBootstrap)((ServerBootstrap)b.group(pGroup, cGroup).channel(NioServerSocketChannel.class)).option(ChannelOption.SO_BACKLOG, 1024)).handler(new LoggingHandler(LogLevel.INFO))).childHandler(new ChannelInitializer() {

protected void initChannel(SocketChannel sc) throws Exception {

sc.pipeline().addLast(new ChannelHandler[]{MarshallingCodeCFactory.buildMarshallingDecoder()});

sc.pipeline().addLast(new ChannelHandler[]{MarshallingCodeCFactory.buildMarshallingEncoder()});

sc.pipeline().addLast(new ChannelHandler[]{new ReadTimeoutHandler(5)});

sc.pipeline().addLast(new ChannelHandler[]{new ServerHandler()});

}

});

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

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

pGroup.shutdownGracefully();

cGroup.shutdownGracefully();

}

}

import io.netty.bootstrap.Bootstrap;

import io.netty.channel.ChannelFuture;

import io.netty.channel.ChannelHandler;

import io.netty.channel.ChannelInitializer;

import io.netty.channel.EventLoopGroup;

import io.netty.channel.nio.NioEventLoopGroup;

import io.netty.channel.socket.SocketChannel;

import io.netty.channel.socket.nio.NioSocketChannel;

import io.netty.handler.logging.LogLevel;

import io.netty.handler.logging.LoggingHandler;

import io.netty.handler.timeout.ReadTimeoutHandler;

import java.util.concurrent.TimeUnit;

public class Client {

private EventLoopGroup group;

private Bootstrap b;

private ChannelFuture cf;

public static Client getInstance() {

return Client.SingletonHolder.instance;

}

private Client() {

this.group = new NioEventLoopGroup();

this.b = new Bootstrap();

((Bootstrap)((Bootstrap)((Bootstrap)this.b.group(this.group)).channel(NioSocketChannel.class)).handler(new LoggingHandler(LogLevel.INFO))).handler(new ChannelInitializer() {

protected void initChannel(SocketChannel sc) throws Exception {

sc.pipeline().addLast(new ChannelHandler[]{MarshallingCodeCFactory.buildMarshallingDecoder()});

sc.pipeline().addLast(new ChannelHandler[]{MarshallingCodeCFactory.buildMarshallingEncoder()});

sc.pipeline().addLast(new ChannelHandler[]{new ReadTimeoutHandler(5)});

sc.pipeline().addLast(new ChannelHandler[]{new ClientHandler()});

}

});

}

public void connect() {

try {

this.cf = this.b.connect(“127.0.0.1”, 8765).sync();

System.out.println(“远程服务器已经连接, 可以进行数据交换..”);

} catch (Exception var2) {

var2.printStackTrace();

}

}

public ChannelFuture getChannelFuture() {

if (this.cf == null) {

this.connect();

}

if (!this.cf.channel().isActive()) {

this.connect();

}

return this.cf;

}

public static void main(String[] args) throws Exception {

final Client c = getInstance();

ChannelFuture cf = c.getChannelFuture();

for(int i = 1; i <= 3; ++i) {

Request request = new Request();

request.setId(“” + i);

request.setName(“pro” + i);

request.setRequestMessage(“数据信息” + i);

cf.channel().writeAndFlush(request);

TimeUnit.SECONDS.sleep(4L);

}

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

(new Thread(new Runnable() {

public void run() {

try {

System.out.println(“进入子线程…”);

ChannelFuture cf = c.getChannelFuture();

System.out.println(cf.channel().isActive());

System.out.println(cf.channel().isOpen());

Request request = new Request();

request.setId(“4”);

request.setName(“pro4”);

request.setRequestMessage(“数据信息4”);

cf.channel().writeAndFlush(request);

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

System.out.println(“子线程结束.”);

} catch (InterruptedException var3) {

var3.printStackTrace();

}

}

})).start();

System.out.println(“断开连接,主线程结束..”);

}

private static class SingletonHolder {

static final Client instance = new Client((Client)null);

private SingletonHolder() {

}

}

}

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/169721.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • 2019年5月25更新——“运动世界校园”软件破解

    一、软件工作原理软件和后台使用API进行交互,在早期版本中API没有鉴权导致可以通过伪造请求来完成跑步,但是后期API迭代了好几个版本,目前认为现在的请求需要间隔一个合理的时间差(跑步时间),而且需要计算一个token用来鉴权,避免了伪造请求。 跑步开始和跑步完成时,会记录时间、设备序列号、IMEI等敏感信息,上传服务器。此操作用来记录手机设备唯一性,用来检测频繁换手机,一台设备上登陆不同账…

    2022年4月7日
    199
  • sqlformat数字格式化_java怎么输出数字

    sqlformat数字格式化_java怎么输出数字前言以前用到要对数字格式的地方,都是直接到网上搜一下。拿过来能用就行。因为平时用的不多。但是最近的项目对这个用的多了。网上拿来的不够用了。自己看了java源码把这方面恶补了。而且最近也好长时间没有写博客了。正好写一篇抛砖引玉吧。正文如果你对java源码比较了解。你会发现java对文字,数字的格式化,是有一个公共的父类的Format。NumberFormat和DecimalFormat都是它…

    2022年10月8日
    2
  • Storm翻版:开源实时数据处理系统Samza

    Storm翻版:开源实时数据处理系统Samza

    2021年9月4日
    73
  • UE4投影矩阵[通俗易懂]

    UE4投影矩阵[通俗易懂]UE4投影矩阵正交投影classFOrthoMatrix :publicFMatrix{public: /** *Constructor * *@paramWidthviewspacewidth *@paramHeightviewspaceheight *@paramZScalescaleintheZaxis *@paramZOffsetoffsetintheZaxis */ FOrthoMatrix(flo

    2022年10月5日
    5
  • 单射双射与满射

    单射双射与满射单射(injection):每一个x都有唯一的y与之对应;满射(surjection):每一个y都必有至少一个x与之对应;双射(又叫一一对应,bijection):每一个x都有y与之对应,每一个y都有x与之对应。把x比作萝卜,y比作坑:单射就是一个萝卜一个坑,有的坑有可能没萝卜;满射就是所有坑都有萝卜,有的坑可能有不止一个萝卜;双射就是严格的一个萝卜一个坑,一个坑一个萝卜,所有萝卜都有坑,所有坑都有萝卜。…

    2022年6月6日
    38
  • oracle数字类型num比较大小,关于类型:Oracle NUMBER比较

    oracle数字类型num比较大小,关于类型:Oracle NUMBER比较通常,在编程中,不应比较浮点数据类型的相等性,因为存储的值通常是近似值。由于两个非整数的OracleNUMBER值存储方式不同(基数为10),是否可以可靠地比较它们的相等性?是的,OracleNUMBER类型是精确的。与浮点/双精度类型相比,它们更像是带刻度的整数。因此NUMBER(10,3)具有10位数字,在小数点后3位,这实际上是10位整数,小数位数为3。实际上,这就是JavaBig…

    2022年7月24日
    32

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号