[转]java nio解决半包 粘包问题
java nio解决半包 粘包问题
package org.weir.socket.socketPackage; import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set; public class NioSocketClient extends Thread {
private SocketChannel socketChannel;
private Selector selector = null;
private int clientId; public static void main(String args[]) throws IOException {
NioSocketClient client = new NioSocketClient();
client.initClient();
client.start();
} public NioSocketClient() {
} public NioSocketClient(int clientId) {
this.clientId = clientId;
} public void initClient() throws IOException {
InetSocketAddress inetSocketAddress = new InetSocketAddress(8888);
selector = Selector.open();
socketChannel = SocketChannel.open();
socketChannel.configureBlocking(false);
socketChannel.connect(inetSocketAddress);
synchronized (selector) {
socketChannel.register(selector, SelectionKey.OP_CONNECT);
}
} public void run() {
while (true) {
try {
int key = selector.select();
if (key > 0) {
Set<SelectionKey> keySet = selector.selectedKeys();
Iterator<SelectionKey> iter = keySet.iterator();
while (iter.hasNext()) {
SelectionKey selectionKey = null;
synchronized (iter) {
selectionKey = iter.next();
iter.remove();
} if (selectionKey.isConnectable()) {
finishConnect(selectionKey);
}
if (selectionKey.isWritable()) {
send(selectionKey);
}
if (selectionKey.isReadable()) {
read(selectionKey);
}
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} public void finishConnect(SelectionKey key) {
System.out.println("client finish connect!");
SocketChannel socketChannel = (SocketChannel) key.channel();
try {
socketChannel.finishConnect();
synchronized (selector) {
socketChannel.register(selector, SelectionKey.OP_WRITE);
key.interestOps(SelectionKey.OP_WRITE); }
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} public void read(SelectionKey key) throws IOException {
SocketChannel channel = (SocketChannel) key.channel();
ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
int len = channel.read(byteBuffer);
if (len > 0) {
byteBuffer.flip();
byte[] byteArray = new byte[byteBuffer.limit()];
byteBuffer.get(byteArray);
System.out.println("client[" + clientId + "]" + "receive from server:");
System.out.println(new String(byteArray));
len = channel.read(byteBuffer);
byteBuffer.clear(); }
key.interestOps(SelectionKey.OP_READ);
} public void send(SelectionKey key) {
SocketChannel channel = (SocketChannel) key.channel(); // byteBuffer.put(ss.getBytes());
for (int i = 0; i < 10; i++) {
String ss = i + "Server ,how are you? this is package message from NioSocketClient!";
ByteBuffer byteBuffer = ByteBuffer.wrap(ss.getBytes()); System.out.println("[client] send:{" + i + "}-- " + ss);
while (byteBuffer.hasRemaining()) {
try { channel.write(byteBuffer);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} // key.interestOps(SelectionKey.OP_READ);
try {
synchronized (selector) { channel.register(selector, SelectionKey.OP_READ);
}
} catch (ClosedChannelException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} /**
* int到byte[]
*
* @param i
* @return
*/
public static byte[] intToBytes(int value) {
byte[] result = new byte[4];
// 由高位到低位
result[0] = (byte) ((value >> 24) & 0xFF);
result[1] = (byte) ((value >> 16) & 0xFF);
result[2] = (byte) ((value >> 8) & 0xFF);
result[3] = (byte) (value & 0xFF);
return result;
}
}
package org.weir.socket.socketPackage; import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set; public class NioSocketServer extends Thread {
ServerSocketChannel serverSocketChannel = null;
Selector selector = null;
SelectionKey selectionKey = null; public void initServer() throws IOException {
selector = Selector.open();
serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.configureBlocking(false);
serverSocketChannel.socket().bind(new InetSocketAddress(8888));
selectionKey = serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT); } public void run() {
while (true) {
try {
int selectKey = selector.select();
if (selectKey > 0) {
Set<SelectionKey> keySet = selector.selectedKeys();
Iterator<SelectionKey> iter = keySet.iterator();
while (iter.hasNext()) {
SelectionKey selectionKey = iter.next();
iter.remove();
if (selectionKey.isAcceptable()) {
accept(selectionKey);
}
if (selectionKey.isReadable()) {
read(selectionKey);
}
if (selectionKey.isWritable()) {
// write(selectionKey);
System.out.println();
}
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
try {
serverSocketChannel.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
} }
} public void accept(SelectionKey key) {
try {
ServerSocketChannel serverSocketChannel = (ServerSocketChannel) key.channel();
SocketChannel socketChannel = serverSocketChannel.accept();
System.out.println("is acceptable");
socketChannel.configureBlocking(false);
socketChannel.register(selector, SelectionKey.OP_READ); } catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} public void read(SelectionKey selectionKey) {
System.out.println("read事件"); try {
SocketChannel channel = (SocketChannel) selectionKey.channel();
ByteBuffer byteBuffer = ByteBuffer.allocate(100);
int len = channel.read(byteBuffer);
if (len > 0) { byteBuffer.flip();
byte[] byteArray = new byte[byteBuffer.limit()];
byteBuffer.get(byteArray);
System.out.println("NioSocketServer receive from client:" + new String(byteArray)); }
selectionKey.interestOps(SelectionKey.OP_READ);
selectionKey.interestOps(SelectionKey.OP_READ);
} catch (IOException e) {
// TODO Auto-generated catch block
try {
serverSocketChannel.close();
selectionKey.cancel();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
e.printStackTrace();
} } public void write(SelectionKey selectionKey) {
SocketChannel socketChannel = (SocketChannel) selectionKey.channel();
String httpResponse = "HTTP/1.1 200 OK\r\n" + "Content-Length: 38\r\n" + "Content-Type: text/html\r\n" + "\r\n"
+ "<html><body>Hello World!</body></html>";
System.out.println("response from server to client");
try {
ByteBuffer byteBuffer = ByteBuffer.wrap(httpResponse.getBytes());
while (byteBuffer.hasRemaining()) {
socketChannel.write(byteBuffer);
}
selectionKey.cancel();
} catch (IOException e) {
try {
selectionKey.cancel();
serverSocketChannel.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// TODO Auto-generated catch block
e.printStackTrace();
}
} /**
* byte[]转int
*
* @param bytes
* @return
*/
public static int byteArrayToInt(byte[] bytes) {
int value = 0;
// 由高位到低位
for (int i = 0; i < 4; i++) {
int shift = (4 - 1 - i) * 8;
value += (bytes[i] & 0x000000FF) << shift;// 往高位游
}
return value;
} public static void main(String args[]) throws IOException {
NioSocketServer server = new NioSocketServer();
server.initServer();
server.start(); }
}
运行这两个类,结果如下:


package org.weir.socket.socketPackage; import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set; public class NioSocketServer extends Thread {
ServerSocketChannel serverSocketChannel = null;
Selector selector = null;
SelectionKey selectionKey = null;
// 缓存一个read事件中一个不完整的包,以待下次read事件到来时拼接成完整的包
ByteBuffer cacheBuffer = ByteBuffer.allocate(100);
boolean cache = false; public void initServer() throws IOException {
selector = Selector.open();
serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.configureBlocking(false);
serverSocketChannel.socket().bind(new InetSocketAddress(8888));
selectionKey = serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT); } public void run() {
while (true) {
try {
int selectKey = selector.select();
if (selectKey > 0) {
Set<SelectionKey> keySet = selector.selectedKeys();
Iterator<SelectionKey> iter = keySet.iterator();
while (iter.hasNext()) {
SelectionKey selectionKey = iter.next();
iter.remove();
if (selectionKey.isAcceptable()) {
accept(selectionKey);
}
if (selectionKey.isReadable()) {
read(selectionKey);
}
if (selectionKey.isWritable()) {
// write(selectionKey);
System.out.println();
}
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
try {
serverSocketChannel.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
} }
} public void accept(SelectionKey key) {
try {
ServerSocketChannel serverSocketChannel = (ServerSocketChannel) key.channel();
SocketChannel socketChannel = serverSocketChannel.accept();
System.out.println("is acceptable");
socketChannel.configureBlocking(false);
socketChannel.register(selector, SelectionKey.OP_READ); } catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} // 一个client的write事件不一定唯一对应server的read事件,所以需要缓存不完整的包,以便拼接成完整的包
//包协议:包=包头(4byte)+包体,包头内容为包体的数据长度
public void read(SelectionKey selectionKey) {
System.out.println("read事件");
int head_length = 4;//数据包长度
byte[] headByte = new byte[4]; try {
SocketChannel channel = (SocketChannel) selectionKey.channel();
ByteBuffer byteBuffer = ByteBuffer.allocate(100);
int bodyLen = -1;
if (cache) {
cacheBuffer.flip();
byteBuffer.put(cacheBuffer);
}
channel.read(byteBuffer);// 当前read事件
byteBuffer.flip();// write mode to read mode
while (byteBuffer.remaining() > 0) {
if (bodyLen == -1) {// 还没有读出包头,先读出包头
if (byteBuffer.remaining() >= head_length) {// 可以读出包头,否则缓存
byteBuffer.mark();
byteBuffer.get(headByte);
bodyLen = byteArrayToInt(headByte);
} else {
byteBuffer.reset();
cache = true;
cacheBuffer.clear();
cacheBuffer.put(byteBuffer);
break;
}
} else {// 已经读出包头
if (byteBuffer.remaining() >= bodyLen) {// 大于等于一个包,否则缓存
byte[] bodyByte = new byte[bodyLen];
byteBuffer.get(bodyByte, 0, bodyLen);
bodyLen = -1; System.out.println("receive from clien content is:" + new String(bodyByte));
} else {
byteBuffer.reset();
cacheBuffer.clear();
cacheBuffer.put(byteBuffer);
cache = true;
break;
}
}
} selectionKey.interestOps(SelectionKey.OP_READ);
} catch (IOException e) {
// TODO Auto-generated catch block
try {
serverSocketChannel.close();
selectionKey.cancel();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
e.printStackTrace();
} } public void write(SelectionKey selectionKey) {
SocketChannel socketChannel = (SocketChannel) selectionKey.channel();
String httpResponse = "HTTP/1.1 200 OK\r\n" + "Content-Length: 38\r\n" + "Content-Type: text/html\r\n" + "\r\n"
+ "<html><body>Hello World!</body></html>";
System.out.println("response from server to client");
try {
ByteBuffer byteBuffer = ByteBuffer.wrap(httpResponse.getBytes());
while (byteBuffer.hasRemaining()) {
socketChannel.write(byteBuffer);
}
selectionKey.cancel();
} catch (IOException e) {
try {
selectionKey.cancel();
serverSocketChannel.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// TODO Auto-generated catch block
e.printStackTrace();
}
} /**
* byte[]转int
*
* @param bytes
* @return
*/
public static int byteArrayToInt(byte[] bytes) {
int value = 0;
// 由高位到低位
for (int i = 0; i < 4; i++) {
int shift = (4 - 1 - i) * 8;
value += (bytes[i] & 0x000000FF) << shift;// 往高位游
}
return value;
} public static void main(String args[]) throws IOException {
NioSocketServer server = new NioSocketServer();
server.initServer();
server.start(); }
}
package org.weir.socket.socketPackage; import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set; public class NioSocketClient extends Thread {
private SocketChannel socketChannel;
private Selector selector = null;
private int clientId; public static void main(String args[]) throws IOException {
NioSocketClient client = new NioSocketClient();
client.initClient();
client.start();
} public NioSocketClient() {
} public NioSocketClient(int clientId) {
this.clientId = clientId;
} public void initClient() throws IOException {
InetSocketAddress inetSocketAddress = new InetSocketAddress(8888);
selector = Selector.open();
socketChannel = SocketChannel.open();
socketChannel.configureBlocking(false);
socketChannel.connect(inetSocketAddress);
synchronized (selector) {
socketChannel.register(selector, SelectionKey.OP_CONNECT);
}
} public void run() {
while (true) {
try {
int key = selector.select();
if (key > 0) {
Set<SelectionKey> keySet = selector.selectedKeys();
Iterator<SelectionKey> iter = keySet.iterator();
while (iter.hasNext()) {
SelectionKey selectionKey = null;
synchronized (iter) {
selectionKey = iter.next();
iter.remove();
} if (selectionKey.isConnectable()) {
finishConnect(selectionKey);
}
if (selectionKey.isWritable()) {
send(selectionKey);
}
if (selectionKey.isReadable()) {
read(selectionKey);
}
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} public void finishConnect(SelectionKey key) {
System.out.println("client finish connect!");
SocketChannel socketChannel = (SocketChannel) key.channel();
try {
socketChannel.finishConnect();
synchronized (selector) {
socketChannel.register(selector, SelectionKey.OP_WRITE);
key.interestOps(SelectionKey.OP_WRITE); }
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} public void read(SelectionKey key) throws IOException {
SocketChannel channel = (SocketChannel) key.channel();
ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
int len = channel.read(byteBuffer);
if (len > 0) {
byteBuffer.flip();
byte[] byteArray = new byte[byteBuffer.limit()];
byteBuffer.get(byteArray);
System.out.println("client[" + clientId + "]" + "receive from server:");
System.out.println(new String(byteArray));
len = channel.read(byteBuffer);
byteBuffer.clear(); }
key.interestOps(SelectionKey.OP_READ);
} public void send(SelectionKey key) {
SocketChannel channel = (SocketChannel) key.channel(); for (int i = 0; i < 10; i++) {
String ss = i + "Server ,how are you? this is package message from NioSocketClient!";
int head = (ss).getBytes().length;
ByteBuffer byteBuffer = ByteBuffer.allocate(4 + head);
byteBuffer.put(intToBytes(head));
byteBuffer.put(ss.getBytes());
byteBuffer.flip();
System.out.println("[client] send:" + i + "-- " + head + ss);
while (byteBuffer.hasRemaining()) {
try { channel.write(byteBuffer);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} // key.interestOps(SelectionKey.OP_READ);
try {
synchronized (selector) { channel.register(selector, SelectionKey.OP_READ);
}
} catch (ClosedChannelException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} /**
* int到byte[]
*
* @param i
* @return
*/
public static byte[] intToBytes(int value) {
byte[] result = new byte[4];
// 由高位到低位
result[0] = (byte) ((value >> 24) & 0xFF);
result[1] = (byte) ((value >> 16) & 0xFF);
result[2] = (byte) ((value >> 8) & 0xFF);
result[3] = (byte) (value & 0xFF);
return result;
}
}
运行结果如下: 
[转]java nio解决半包 粘包问题的更多相关文章
- tomcat Http11NioProtocol如何解析http请求及如何解决TCP拆包粘包
前言 tomcat是常用的Web 应用服务器,目前国内有很多文章讲解了tomcat架构,请求流程等,但是没有如何解析http请求及如何解决TCP粘包拆包,所以这篇文章的目的就是介绍这块内容,一下内容完 ...
- java nio消息半包、粘包解决方案
问题背景 NIO是面向缓冲区进行通信的,不是面向流的.我们都知道,既然是缓冲区,那它一定存在一个固定大小.这样一来通常会遇到两个问题: 消息粘包:当缓冲区足够大,由于网络不稳定种种原因,可能会有多条消 ...
- 6行代码解决golang TCP粘包
转自:https://studygolang.com/articles/12483 什么是TCP粘包问题以及为什么会产生TCP粘包,本文不加讨论.本文使用golang的bufio.Scanner来实现 ...
- 用struct模块解决tcp的粘包问题
服务器端程序 import struct import socket sk = socket.socket() sk.bind(('127.0.0.1',9000)) sk.listen() conn ...
- netty10---分包粘包
客户端:根据 长度+数据 方式发送 package com.server; import java.net.Socket; import java.nio.ByteBuffer; public cla ...
- 网络编程3 网络编程之缓冲区&subprocess&粘包&粘包解决方案
1.sub简单使用 2.粘包现象(1) 3.粘包现象(2) 4.粘包现象解决方案 5.struct学习 6.粘包现象升级版解决方案 7.打印进度条
- mina框架tcpt通讯接收数据断包粘包处理
用mina做基于tcp,udp有通讯有段时间了,一直对编码解码不是很熟悉,这次做项目的时候碰到了断包情况,贴一下解决过程, 我接受数据格式如下图所示: unit32为c++中数据类型,代表4个字节,由 ...
- goim socket丢包粘包问题解决。
-(NSInteger)bytesToInt:(unsigned char*) data { return (data[3]&255)|(data[2]&255)<<8|( ...
- Netty解决TCP粘包/拆包问题 - 按行分隔字符串解码器
服务端 package org.zln.netty.five.timer; import io.netty.bootstrap.ServerBootstrap; import io.netty.cha ...
随机推荐
- React native中的组建通知通信:
有这么一个需求,在B页面pop()回到A页面,需要A页面执行刷新,那么我们可以采用以下方法: 1:在A页面Push到B页面中,加上一个A页面中的刷新函数做为参数,然后在B页面中在pop()函数封装后通 ...
- JAVA 面向对象中的多态
多态是继封装.继承之后,面向对象的第三大特性. 现实事物经常会体现出多种形态,如学生,学生是人的一种,则一个具体的同学张三既是学生也是人,即出现两种形态. Java作为面向对象的语言,同样可以描述一个 ...
- NoSQL(not only struts query language)的简单介绍
为什么需要NoSQL? 互联网自扩大规模来一直面临3个问题 1.High performance高并发 一个网站开发实时生成动态页面可能会存在高并发请求的需求,硬盘IO已经无法接受 2.Huge St ...
- Python 传递任意数量的实参
在定义函数的时候如果你不知道该函数在使用的时候要接收多少的实参怎么办? 好在python提供了可以接收任意数量的实参的操作. # def sandwitch(*ingredents): # print ...
- Mac python Tesseract 验证码识别
Tesseract 简介 Tesseract(/'tesərækt/) 这个词的意思是"超立方体",指的是几何学里的四维标准方体,又称"正八胞体".不过这里要讲 ...
- [Spring] 04 Denpendency Injection
DI Dependency Injection 依赖注入:从程序代码中移除依赖关系的一种设计模式. 这样就可以更容易地管理和测试应用程序. DI使我们的程序编码 loosely coupled.松耦合 ...
- 雷林鹏分享:XML 验证
XML 验证 拥有正确语法的 XML 被称为"形式良好"的 XML. 通过 DTD 验证的XML是"合法"的 XML. 形式良好的 XML 文档 "形 ...
- every day a practice —— morning(6)
"Nearly one in five job ads for China's 2018 national civil service called for 'men only' or 'm ...
- 【异常及源码分析】org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.type.TypeException: Could not set parameters for mapping: ParameterMapping
一.异常出现的场景 1)异常出现的SQL @Select("SELECT\n" + " id,discount_type ,min_charge, ${cardFee} ...
- LeetCode--387--字符串中的第一个唯一字符
问题描述: 给定一个字符串,找到它的第一个不重复的字符,并返回它的索引.如果不存在,则返回 -1. 案例: s = "leetcode" 返回 0. s = "lovel ...