提交 0e037396 编写于 作者: 檀越@新空间's avatar 檀越@新空间 🐭

Initial commit

上级
# Default ignored files
/shelf/
/workspace.xml
# Datasource local storage ignored files
/dataSources/
/dataSources.local.xml
# Editor-based HTTP Client requests
/httpRequests/
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="CompilerConfiguration">
<annotationProcessing>
<profile default="true" name="Default" enabled="true" />
<profile name="Maven default annotation processors profile" enabled="true">
<sourceOutputDir name="target/generated-sources/annotations" />
<sourceTestOutputDir name="target/generated-test-sources/test-annotations" />
<outputRelativeToContentRoot value="true" />
<module name="netty-demo" />
</profile>
</annotationProcessing>
</component>
</project>
\ No newline at end of file
此差异已折叠。
<component name="InspectionProjectProfileManager">
<profile version="1.0">
<option name="myName" value="Project Default" />
<inspection_tool class="AlibabaAvoidCommentBehindStatement" enabled="false" level="MAJOR" enabled_by_default="false" />
<inspection_tool class="JavaDoc" enabled="true" level="WARNING" enabled_by_default="true">
<option name="TOP_LEVEL_CLASS_OPTIONS">
<value>
<option name="ACCESS_JAVADOC_REQUIRED_FOR" value="none" />
<option name="REQUIRED_TAGS" value="" />
</value>
</option>
<option name="INNER_CLASS_OPTIONS">
<value>
<option name="ACCESS_JAVADOC_REQUIRED_FOR" value="none" />
<option name="REQUIRED_TAGS" value="" />
</value>
</option>
<option name="METHOD_OPTIONS">
<value>
<option name="ACCESS_JAVADOC_REQUIRED_FOR" value="none" />
<option name="REQUIRED_TAGS" value="@return@param@throws or @exception" />
</value>
</option>
<option name="FIELD_OPTIONS">
<value>
<option name="ACCESS_JAVADOC_REQUIRED_FOR" value="none" />
<option name="REQUIRED_TAGS" value="" />
</value>
</option>
<option name="IGNORE_DEPRECATED" value="false" />
<option name="IGNORE_JAVADOC_PERIOD" value="true" />
<option name="IGNORE_DUPLICATED_THROWS" value="false" />
<option name="IGNORE_POINT_TO_ITSELF" value="false" />
<option name="myAdditionalJavadocTags" value="date" />
</inspection_tool>
</profile>
</component>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="RemoteRepositoriesConfiguration">
<remote-repository>
<option name="id" value="central" />
<option name="name" value="Central Repository" />
<option name="url" value="https://maven.aliyun.com/nexus/content/groups/public/" />
</remote-repository>
<remote-repository>
<option name="id" value="central" />
<option name="name" value="Maven Central repository" />
<option name="url" value="https://repo1.maven.org/maven2" />
</remote-repository>
<remote-repository>
<option name="id" value="jboss.community" />
<option name="name" value="JBoss Community repository" />
<option name="url" value="https://repository.jboss.org/nexus/content/repositories/public/" />
</remote-repository>
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="CodeInsightWorkspaceSettings">
<option name="optimizeImportsOnTheFly" value="true" />
</component>
<component name="ExternalStorageConfigurationManager" enabled="true" />
<component name="MavenProjectsManager">
<option name="originalFiles">
<list>
<option value="$PROJECT_DIR$/pom.xml" />
</list>
</option>
</component>
<component name="ProjectRootManager" version="2" languageLevel="JDK_1_8" default="true" project-jdk-name="1.8" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/out" />
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="Palette2">
<group name="Swing">
<item class="com.intellij.uiDesigner.HSpacer" tooltip-text="Horizontal Spacer" icon="/com/intellij/uiDesigner/icons/hspacer.png" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="1" hsize-policy="6" anchor="0" fill="1" />
</item>
<item class="com.intellij.uiDesigner.VSpacer" tooltip-text="Vertical Spacer" icon="/com/intellij/uiDesigner/icons/vspacer.png" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="1" anchor="0" fill="2" />
</item>
<item class="javax.swing.JPanel" icon="/com/intellij/uiDesigner/icons/panel.png" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="3" hsize-policy="3" anchor="0" fill="3" />
</item>
<item class="javax.swing.JScrollPane" icon="/com/intellij/uiDesigner/icons/scrollPane.png" removable="false" auto-create-binding="false" can-attach-label="true">
<default-constraints vsize-policy="7" hsize-policy="7" anchor="0" fill="3" />
</item>
<item class="javax.swing.JButton" icon="/com/intellij/uiDesigner/icons/button.png" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="3" anchor="0" fill="1" />
<initial-values>
<property name="text" value="Button" />
</initial-values>
</item>
<item class="javax.swing.JRadioButton" icon="/com/intellij/uiDesigner/icons/radioButton.png" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="3" anchor="8" fill="0" />
<initial-values>
<property name="text" value="RadioButton" />
</initial-values>
</item>
<item class="javax.swing.JCheckBox" icon="/com/intellij/uiDesigner/icons/checkBox.png" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="3" anchor="8" fill="0" />
<initial-values>
<property name="text" value="CheckBox" />
</initial-values>
</item>
<item class="javax.swing.JLabel" icon="/com/intellij/uiDesigner/icons/label.png" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="0" anchor="8" fill="0" />
<initial-values>
<property name="text" value="Label" />
</initial-values>
</item>
<item class="javax.swing.JTextField" icon="/com/intellij/uiDesigner/icons/textField.png" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1">
<preferred-size width="150" height="-1" />
</default-constraints>
</item>
<item class="javax.swing.JPasswordField" icon="/com/intellij/uiDesigner/icons/passwordField.png" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1">
<preferred-size width="150" height="-1" />
</default-constraints>
</item>
<item class="javax.swing.JFormattedTextField" icon="/com/intellij/uiDesigner/icons/formattedTextField.png" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1">
<preferred-size width="150" height="-1" />
</default-constraints>
</item>
<item class="javax.swing.JTextArea" icon="/com/intellij/uiDesigner/icons/textArea.png" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JTextPane" icon="/com/intellij/uiDesigner/icons/textPane.png" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JEditorPane" icon="/com/intellij/uiDesigner/icons/editorPane.png" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JComboBox" icon="/com/intellij/uiDesigner/icons/comboBox.png" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="2" anchor="8" fill="1" />
</item>
<item class="javax.swing.JTable" icon="/com/intellij/uiDesigner/icons/table.png" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JList" icon="/com/intellij/uiDesigner/icons/list.png" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="2" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JTree" icon="/com/intellij/uiDesigner/icons/tree.png" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JTabbedPane" icon="/com/intellij/uiDesigner/icons/tabbedPane.png" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="3" hsize-policy="3" anchor="0" fill="3">
<preferred-size width="200" height="200" />
</default-constraints>
</item>
<item class="javax.swing.JSplitPane" icon="/com/intellij/uiDesigner/icons/splitPane.png" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="3" hsize-policy="3" anchor="0" fill="3">
<preferred-size width="200" height="200" />
</default-constraints>
</item>
<item class="javax.swing.JSpinner" icon="/com/intellij/uiDesigner/icons/spinner.png" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1" />
</item>
<item class="javax.swing.JSlider" icon="/com/intellij/uiDesigner/icons/slider.png" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1" />
</item>
<item class="javax.swing.JSeparator" icon="/com/intellij/uiDesigner/icons/separator.png" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3" />
</item>
<item class="javax.swing.JProgressBar" icon="/com/intellij/uiDesigner/icons/progressbar.png" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="0" fill="1" />
</item>
<item class="javax.swing.JToolBar" icon="/com/intellij/uiDesigner/icons/toolbar.png" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="0" fill="1">
<preferred-size width="-1" height="20" />
</default-constraints>
</item>
<item class="javax.swing.JToolBar$Separator" icon="/com/intellij/uiDesigner/icons/toolbarSeparator.png" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="0" anchor="0" fill="1" />
</item>
<item class="javax.swing.JScrollBar" icon="/com/intellij/uiDesigner/icons/scrollbar.png" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="0" anchor="0" fill="2" />
</item>
</group>
</component>
</project>
\ No newline at end of file
onetwothree
\ No newline at end of file
helloworld秦书予
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.kwan</groupId>
<artifactId>netty-demo</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.1.70.Final</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>2.0.23</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.26</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.28</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>1.7.28</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.8</version>
</dependency>
</dependencies>
</project>
\ No newline at end of file
package com.kwan.shuyu.heima.bytebuffer;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;
/**
* ByteBuffer写入文件
*
* @author : qinyingjie
* @version : 2.2.0
* @date : 2023/4/18 17:15
*/
public class ByteBuffer_001_Write {
public static void main(String[] args) {
final ByteBuffer b1 = StandardCharsets.UTF_8.encode("hello");
final ByteBuffer b2 = StandardCharsets.UTF_8.encode("world");
final ByteBuffer b3 = StandardCharsets.UTF_8.encode("秦书予");
//绝对目录
//final String path = "/Users/qinyingjie/Documents/idea-workspace/netty-demo/src/main/resources/word2.txt";
//相对目录
final String path = "word2.txt";
try (FileChannel channel = new RandomAccessFile(path, "rw").getChannel()) {
channel.write(new ByteBuffer[]{b1, b2, b3});
} catch (Exception e) {
e.printStackTrace();
}
}
}
package com.kwan.shuyu.heima.bytebuffer;
import com.kwan.shuyu.until.ByteBufferUtil;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
/**
* 读取文件内容并打印ByteBuffer
*
* @author : qinyingjie
* @version : 2.2.0
* @date : 2023/4/18 18:01
*/
public class ByteBuffer_002_Read {
public static void main(String[] args) {
try (RandomAccessFile file = new RandomAccessFile("/Users/qinyingjie/Documents/idea-workspace/ant/ant-netty/src/main/java/com/xiaofei/antnetty/3parts.txt", "rw")) {
FileChannel channel = file.getChannel();
ByteBuffer a = ByteBuffer.allocate(3);
ByteBuffer b = ByteBuffer.allocate(3);
ByteBuffer c = ByteBuffer.allocate(5);
channel.read(new ByteBuffer[]{a, b, c});
a.flip();
b.flip();
c.flip();
ByteBufferUtil.debugRead(a);
ByteBufferUtil.debugRead(b);
ByteBufferUtil.debugRead(c);
} catch (IOException e) {
e.printStackTrace();
}
}
}
package com.kwan.shuyu.heima.bytebuffer;
/**
* 分割数据
*
* @author : qinyingjie
* @version : 2.2.0
* @date : 2023/4/18 17:15
*/
public class ByteBuffer_003_split {
public static void main(String[] args) {
}
}
package com.kwan.shuyu.heima.nio.nio_001_block;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SocketChannel;
/**
* NioClient 客户端
* <p>
* 发消息:sc.write(Charset.defaultCharset().encode("hi!"))
*
* @author : qinyingjie
* @version : 2.2.0
* @date : 2023/4/18 18:22
*/
public class NioClient {
public static void main(String[] args) throws IOException {
//创建SocketChannel
SocketChannel sc = SocketChannel.open();
//建立和服务端的连接
sc.connect(new InetSocketAddress(8080));
System.out.println("waiting ..............");
}
}
package com.kwan.shuyu.heima.nio.nio_001_block;
import com.kwan.shuyu.until.ByteBufferUtil;
import lombok.extern.slf4j.Slf4j;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.List;
/**
* NioServer 服务端 单线程模拟阻塞模式
*
* @author : qinyingjie
* @version : 2.2.0
* @date : 2023/4/18 18:22
*/
@Slf4j
public class NioServer {
public static void main(String[] args) throws IOException {
//预设ByteBuffer,并分配空间,为了读取数据
final ByteBuffer buffer = ByteBuffer.allocate(16);
//创建ServerSocketChannel
final ServerSocketChannel ssc = ServerSocketChannel.open();
//绑定端口号
ssc.bind(new InetSocketAddress(8080));
//保存SocketChannel集合
List<SocketChannel> channels = new ArrayList<>();
while (true) {
log.info("connecting......");
//等待建立连接
final SocketChannel sc = ssc.accept();
log.info("connected.... {}", sc);
//建立连接后加入集合
channels.add(sc);
//遍历channels集合
for (SocketChannel channel : channels) {
log.info("before read.... {}", channel);
//读取ByteBuffer内容
channel.read(buffer);
//切换为读模式
buffer.flip();
ByteBufferUtil.debugRead(buffer);
//切换为写模式
buffer.clear();
log.info("alfter read.... {}", channel);
}
}
}
}
package com.kwan.shuyu.heima.nio.nio_002_no_block;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SocketChannel;
/**
* NioClient 客户端
* <p>
* 发消息:sc.write(Charset.defaultCharset().encode("hi!"))
*
* @author : qinyingjie
* @version : 2.2.0
* @date : 2023/4/18 18:22
*/
public class NioClient {
public static void main(String[] args) throws IOException {
//创建SocketChannel
SocketChannel sc = SocketChannel.open();
//建立和服务端的连接
sc.connect(new InetSocketAddress(8080));
System.out.println("waiting ..............");
}
}
package com.kwan.shuyu.heima.nio.nio_002_no_block;
import com.kwan.shuyu.until.ByteBufferUtil;
import lombok.extern.slf4j.Slf4j;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.List;
/**
* NioServer 服务端
*
* @author : qinyingjie
* @version : 2.2.0
* @date : 2023/4/18 18:22
*/
@Slf4j
public class NioServer {
public static void main(String[] args) throws IOException {
//预设ByteBuffer,并分配空间,为了读取数据
final ByteBuffer buffer = ByteBuffer.allocate(16);
//创建ServerSocketChannel
final ServerSocketChannel ssc = ServerSocketChannel.open();
//绑定端口号
ssc.bind(new InetSocketAddress(8080));
ssc.configureBlocking(false);
//保存SocketChannel集合
List<SocketChannel> channels = new ArrayList<>();
while (true) {
log.info("connecting......");
//等待建立连接
final SocketChannel sc = ssc.accept();
if (sc != null) {
log.info("connected.... {}", sc);
sc.configureBlocking(false);//非阻塞模式
//建立连接后加入集合
channels.add(sc);
}
//遍历channels集合
for (SocketChannel channel : channels) {
log.info("before read.... {}", channel);
//读取ByteBuffer内容
final int read = channel.read(buffer);//非阻塞读
if (read > 0) {
//切换为读模式
buffer.flip();
ByteBufferUtil.debugRead(buffer);
//切换为写模式
buffer.clear();
log.info("alfter read.... {}", channel);
}
}
}
}
}
package com.kwan.shuyu.heima.nio.nio_003_selector;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SocketChannel;
/**
* NioClient 客户端
* <p>
* 发消息:sc.write(Charset.defaultCharset().encode("hi!"))
*
* @author : qinyingjie
* @version : 2.2.0
* @date : 2023/4/18 18:22
*/
public class NioClient {
public static void main(String[] args) throws IOException {
//创建SocketChannel
SocketChannel sc = SocketChannel.open();
//建立和服务端的连接
sc.connect(new InetSocketAddress(8080));
System.out.println("waiting ..............");
}
}
package com.kwan.shuyu.heima.nio.nio_003_selector;
import com.kwan.shuyu.until.ByteBufferUtil;
import lombok.extern.slf4j.Slf4j;
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;
/**
* NioServer 服务端
*
* @author : qinyingjie
* @version : 2.2.0
* @date : 2023/4/18 18:22
*/
@Slf4j
public class NioServer {
public static void main(String[] args) throws IOException {
final Selector selector = Selector.open();
//预设ByteBuffer,并分配空间,为了读取数据
final ByteBuffer buffer = ByteBuffer.allocate(16);
//创建ServerSocketChannel
final ServerSocketChannel ssc = ServerSocketChannel.open();
//绑定端口号
ssc.configureBlocking(false);
//ServerSocketChannel注册到Selector中
final SelectionKey sscKey = ssc.register(selector, 0, null);
sscKey.interestOps(SelectionKey.OP_ACCEPT);
log.info("sscKey={}", sscKey);
ssc.bind(new InetSocketAddress(8080));
while (true) {
//select方法,没有事件发生,线程阻塞,有事件,线程才会恢复运行
//select在事件未处理时,它不会阻塞,会一直请求处理
selector.select();
final Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
while (iterator.hasNext()) {
final SelectionKey key = iterator.next();
iterator.remove();
log.info("key={}", key);
if (key.isAcceptable()) {
final ServerSocketChannel channel = (ServerSocketChannel) key.channel();
final SocketChannel sc = channel.accept();
sc.configureBlocking(false);
final SelectionKey scKey = sc.register(selector, 0, null);
scKey.interestOps(SelectionKey.OP_READ);
log.info("sc={}", sc);
log.info("scKey={}", scKey);
} else if (key.isReadable()) {
try {
final SocketChannel channel = (SocketChannel) key.channel();
ByteBuffer bf = ByteBuffer.allocate(16);
channel.read(bf);
bf.flip();
ByteBufferUtil.debugRead(bf);
} catch (IOException e) {
e.printStackTrace();
key.cancel();//取消事件处理
}
}
}
}
}
}
\ No newline at end of file
package com.kwan.shuyu.kuangshen.lesson1;
import lombok.extern.slf4j.Slf4j;
import java.net.InetAddress;
/**
* InetAddress类解读
*
* @author : qinyingjie
* @version : 2.2.0
* @date : 2023/3/18 14:15
*/
@Slf4j
public class Basic_001_InetAddress {
public static void main(String[] args) throws Exception {
//获取本机地址信息
InetAddress localIp = InetAddress.getLocalHost();
log.info("localIp.getCanonicalHostName()=" + localIp.getCanonicalHostName());//localhost
log.info("localIp.getHostAddress()=" + localIp.getHostAddress());//127.0.0.1
log.info("localIp.getHostName()=" + localIp.getHostName());//qinyingjiedeMacBook-Pro.local
log.info("localIp.toString()=" + localIp.toString());//qinyingjiedeMacBook-Pro.local/127.0.0.1
log.info("localIp.isReachable(5000)=" + localIp.isReachable(3000));//true
//获取指定域名地址信息
log.info("====================================");
InetAddress baiduIp = InetAddress.getByName("www.baidu.com");
log.info("baiduIp.getCanonicalHostName()=" + baiduIp.getCanonicalHostName());//14.119.104.189
log.info("baiduIp.getHostAddress()=" + baiduIp.getHostAddress());//14.119.104.189
log.info("baiduIp.getHostName()=" + baiduIp.getHostName());//www.baidu.com
log.info("baiduIp.toString()=" + baiduIp.toString());//www.baidu.com/14.119.104.189
log.info("baiduIp.isReachable(5000)=" + baiduIp.isReachable(5000));//false
log.info("====================================");
//获取指定原始IP地址信息
InetAddress ip = InetAddress.getByAddress(new byte[]{127, 0, 0, 1});
log.info("ip.getCanonicalHostName()=" + ip.getCanonicalHostName());//localhost
log.info("ip.getHostAddress()= " + ip.getHostAddress());//127.0.0.1
log.info("ip.getHostName()=" + ip.getHostName());//localhost
log.info("ip.toString()=" + ip.toString());//localhost/127.0.0.1
log.info("ip.isReachable(5000)=" + ip.isReachable(5000));//true
}
}
\ No newline at end of file
package com.kwan.shuyu.kuangshen.lesson2;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
/**
* 客户端 socket client
*
* @author : qinyingjie
* @version : 2.2.0
* @date : 2023/3/19 00:12
*/
public class Basic_001_Client {
public static void main(String[] args) throws Exception {
InetAddress inetAddress = InetAddress.getByName("127.0.0.1");
int port = 9999;
Socket socket = new Socket(inetAddress, port);
OutputStream outputStream = socket.getOutputStream();
outputStream.write("你好".getBytes());
outputStream.close();
socket.close();
}
}
\ No newline at end of file
package com.kwan.shuyu.kuangshen.lesson2;
import lombok.extern.slf4j.Slf4j;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
/**
* 服务端 socket server
*
* @author : qinyingjie
* @version : 2.2.0
* @date : 2023/3/18 14:15
*/
@Slf4j
public class Basic_002_Server {
public static void main(String[] args) throws Exception {
ServerSocket serverSocket = new ServerSocket(9999);
while (true) {
Socket socket = serverSocket.accept();
InputStream inputStream = socket.getInputStream();
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
final byte[] buffer = new byte[1024];
int len = 0;
while ((len = inputStream.read(buffer)) != -1) {
byteArrayOutputStream.write(buffer, 0, len);
}
log.info(byteArrayOutputStream.toString());
byteArrayOutputStream.close();
inputStream.close();
socket.close();
}
}
}
\ No newline at end of file
package com.kwan.shuyu.kuangshen.lesson3;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
/**
* 上传文件
*
* @author : qinyingjie
* @version : 2.2.0
* @date : 2023/3/19 11:24
*/
public class File_001_client {
public static void main(String[] args) throws Exception {
//1.创建一个socket
Socket socket = new Socket(InetAddress.getByName("127.0.0.1"), 9000);
//2.创建一个输出流
OutputStream os = socket.getOutputStream();
//3.文件流
final FileInputStream fileIs = new FileInputStream("/Users/qinyingjie/Documents/idea-workspace/ant/ant-netty/src/main/java/Electron.png");
//4.写出文件
final byte[] buffer = new byte[1024];
int len = 0;
while ((len = fileIs.read(buffer)) != -1) {
os.write(buffer, 0, len);
}
//5.关闭资源
fileIs.close();
os.close();
socket.close();
}
}
\ No newline at end of file
package com.kwan.shuyu.kuangshen.lesson3;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
/**
* 下载文件
*
* @author : qinyingjie
* @version : 2.2.0
* @date : 2023/3/19 11:24
*/
public class File_002_server {
public static void main(String[] args) throws Exception {
//1.创建服务
ServerSocket serverSocket = new ServerSocket(9000);
//2.监听客户端连接
Socket socket = serverSocket.accept();
//3.获取输入流
InputStream inputStream = socket.getInputStream();
//4.文件输出
FileOutputStream fileOut = new FileOutputStream("/Users/qinyingjie/Documents/idea-workspace/ant/ant-netty/src/main/java/receive.png");
final byte[] buffer = new byte[1024];
int len;
while ((len = inputStream.read(buffer)) != -1) {
fileOut.write(buffer, 0, len);
}
//5.关闭资源
fileOut.close();
inputStream.close();
socket.close();
}
}
\ No newline at end of file
package com.kwan.shuyu.kuangshen.lesson4;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
/**
* 客户端 udp client
*
* @author : qinyingjie
* @version : 2.2.0
* @date : 2023/3/19 11:24
*/
public class UDP_001_client {
public static void main(String[] args) throws Exception {
//1.创建一个socket
DatagramSocket socket = new DatagramSocket();
//2.建立一个包
String msg = "你好";
final InetAddress inetAddress = InetAddress.getByName("localhost");
int port = 9090;
DatagramPacket packet = new DatagramPacket(msg.getBytes(), 0, msg.getBytes().length, inetAddress, port);
//3.发送
socket.send(packet);
//4.关闭资源
socket.close();
}
}
\ No newline at end of file
package com.kwan.shuyu.kuangshen.lesson4;
import lombok.extern.slf4j.Slf4j;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
/**
* 服务端 udp server
*
* @author : qinyingjie
* @version : 2.2.0
* @date : 2023/3/19 11:24
*/
@Slf4j
public class UDP_002_server {
public static void main(String[] args) throws Exception {
//1.创建socket
DatagramSocket socket = new DatagramSocket(9090);
//2.接收数据包
final byte[] buffer = new byte[1024];
DatagramPacket packet = new DatagramPacket(buffer, 0, buffer.length);
socket.receive(packet);
log.info(packet.getAddress().getHostAddress());
log.info(new String(packet.getData(), 0, packet.getLength()));
//3.关闭资源
socket.close();
}
}
\ No newline at end of file
package com.kwan.shuyu.kuangshen.lesson5;
import org.apache.commons.lang3.StringUtils;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
/**
* 发送端 udp
*
* @author : qinyingjie
* @version : 2.2.0
* @date : 2023/3/19 11:24
*/
public class Chat_001_send {
public static void main(String[] args) throws Exception {
//1.创建一个socket
DatagramSocket socket = new DatagramSocket(8888);
//2.控制台输入
final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
while (true) {
final String data = reader.readLine();
final byte[] datas = data.getBytes();
final DatagramPacket packet = new DatagramPacket(datas, 0, datas.length, new InetSocketAddress("localhost", 6666));
//3.发送
socket.send(packet);
if (StringUtils.equalsIgnoreCase(data, "bye")) {
break;
}
}
//4.关闭资源
socket.close();
}
}
\ No newline at end of file
package com.kwan.shuyu.kuangshen.lesson5;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
/**
* 接收端 udp
*
* @author : qinyingjie
* @version : 2.2.0
* @date : 2023/3/19 11:24
*/
@Slf4j
public class Chat_002_receive {
public static void main(String[] args) throws Exception {
//1.创建socket
DatagramSocket socket = new DatagramSocket(6666);
while (true) { //2.接收数据包
final byte[] buffer = new byte[1024];
DatagramPacket packet = new DatagramPacket(buffer, 0, buffer.length);
socket.receive(packet);
//断开连接 bye
final byte[] data = packet.getData();
final String receive = new String(data, 0, packet.getLength());
log.info(receive);
if (StringUtils.equalsIgnoreCase(receive, "bye")) {
break;
}
}
//3.关闭资源
socket.close();
}
}
\ No newline at end of file
package com.kwan.shuyu.kuangshen.lesson6;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
/**
* 多线程接收
*
* @author : qinyingjie
* @version : 2.2.0
* @date : 2023/3/19 12:16
*/
@Slf4j
public class TalkReceive implements Runnable {
private DatagramSocket socket;
private final int port;
private final String msgFrom;
@SneakyThrows
public TalkReceive(int port, String msgFrom) {
this.port = port;
this.msgFrom = msgFrom;
this.socket = new DatagramSocket(port);
}
@SneakyThrows
@Override
public void run() {
//1.创建socket
while (true) { //2.接收数据包
final byte[] buffer = new byte[1024];
DatagramPacket packet = new DatagramPacket(buffer, 0, buffer.length);
socket.receive(packet);
//断开连接 bye
final byte[] data = packet.getData();
final String receive = new String(data, 0, packet.getLength());
log.info(msgFrom + ": " + receive);
if (StringUtils.equalsIgnoreCase(receive, "bye")) {
break;
}
}
//3.关闭资源
socket.close();
}
}
package com.kwan.shuyu.kuangshen.lesson6;
import lombok.SneakyThrows;
import org.apache.commons.lang3.StringUtils;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
/**
* 多线程发送
*
* @author : qinyingjie
* @version : 2.2.0
* @date : 2023/3/19 12:16
*/
public class TalkSend implements Runnable {
DatagramSocket socket;
BufferedReader reader;
private final int fromPort;
private final String toIp;
private final int toPort;
public TalkSend(int fromPort, String toIp, int toPort) throws Exception {
this.fromPort = fromPort;
this.toIp = toIp;
this.toPort = toPort;
//1.创建一个socket
this.socket = new DatagramSocket(fromPort);
//2.控制台输入
this.reader = new BufferedReader(new InputStreamReader(System.in));
}
@SneakyThrows
@Override
public void run() {
while (true) {
final String data = reader.readLine();
final byte[] datas = data.getBytes();
final DatagramPacket packet = new DatagramPacket(datas, 0, datas.length, new InetSocketAddress(this.toIp, this.toPort));
//3.发送
socket.send(packet);
if (StringUtils.equalsIgnoreCase(data, "bye")) {
break;
}
}
//4.关闭资源
socket.close();
}
}
package com.kwan.shuyu.kuangshen.lesson6;
public class TalkStuden {
public static void main(String[] args) throws Exception {
new Thread(new TalkSend(7777, "localhost", 9999)).start();
new Thread(new TalkReceive(8888, "老师")).start();
}
}
package com.kwan.shuyu.kuangshen.lesson6;
public class TalkTeacher {
public static void main(String[] args) throws Exception {
new Thread(new TalkSend(5555, "localhost", 8888)).start();
new Thread(new TalkReceive(9999, "学生")).start();
}
}
package com.kwan.shuyu.kuangshen.lesson7;
import lombok.extern.slf4j.Slf4j;
import java.net.URL;
/**
* URL常用方法解析
*
* @author : qinyingjie
* @version : 2.2.0
* @date : 2023/3/19 12:37
*/
@Slf4j
public class UrlDemo {
public static void main(String[] args) throws Exception {
final URL url = new URL("http://localhost:8080/helloworld/index.jsp?username=kuangshen&password=123");
log.info(url.getAuthority());//localhost:8080
log.info(url.getPath());///helloworld/index.jsp
log.info(url.getProtocol());//http
log.info(url.getHost());//localhost
log.info(url.getFile());///helloworld/index.jsp?username=kuangshen&password=123
log.info(url.getUserInfo());//null
log.info(url.getQuery());//username=kuangshen&password=123
log.info(url.getRef());//null
log.info(String.valueOf(url.getDefaultPort()));//80
log.info((String) url.getContent());
}
}
package com.kwan.shuyu.netty;
import com.kwan.shuyu.netty.handler.IProtocalHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
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.nio.NioServerSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.CharsetUtil;
import io.netty.util.concurrent.DefaultEventExecutorGroup;
public class Server {
private static void start(int port) throws InterruptedException {
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap b = new ServerBootstrap();//Bootstrap for client
b.group(bossGroup, workerGroup);
b.channel(NioServerSocketChannel.class);//always
b.childHandler(new ChannelInitializer() {
@Override
protected void initChannel(Channel ch) throws Exception {
//ch.pipeline().addLast(new PrintInboundHandler("id1"));
// ch.pipeline().addLast(new LineBasedFrameDecoder(80,false,false));
// ch.pipeline().addLast(new StringDecoder());
// ch.pipeline().addLast(new EchoHandler());
ch.pipeline().addLast(new LengthFieldBasedFrameDecoder(1024, 2, 2, -2, 0));
ch.pipeline().addLast(new DefaultEventExecutorGroup(16), new IProtocalHandler());
ch.pipeline().addLast(new StringEncoder(CharsetUtil.UTF_8));
}
});
ChannelFuture f = b.bind(port).sync();
f.channel().closeFuture().sync();
} finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
public static void main(String[] args) throws InterruptedException {
start(8084);
}
}
\ No newline at end of file
package com.kwan.shuyu.netty;
public class TestNetty {
public static void main(String[] args) {
}
}
package com.kwan.shuyu.netty.handler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
public class EchoHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
String in = (String) msg;
ctx.channel().writeAndFlush(in);
}
}
package com.kwan.shuyu.netty.handler;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;
import java.util.Random;
public class IProtocalHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, final Object msg) throws Exception {
int sleep = 500 * new Random().nextInt(5);
System.out.println("sleep:" + sleep);
Thread.sleep(sleep);
final ByteBuf buf = (ByteBuf) msg;
char c1 = (char) buf.readByte();
char c2 = (char) buf.readByte();
if (c1 != 'J' || c2 != 'W') {
ctx.fireExceptionCaught(new Exception("magic error"));
return ;
}
buf.readShort();//skip length
String outputStr = buf.toString(CharsetUtil.UTF_8);
System.out.println(outputStr);
ctx.channel().writeAndFlush(outputStr+"\n");
}
}
package com.kwan.shuyu.netty.handler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandler;
public class PrintInboundHandler implements ChannelInboundHandler {
private final String id;
public PrintInboundHandler(String id) {
this.id = id;
}
@Override
public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
System.out.println("handlerAdded " + id);
}
@Override
public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
System.out.println("handlerRemoved " + id);
}
@Override
public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
System.out.println("channelRegistered " + id);
ctx.fireChannelRegistered();
}
@Override
public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
System.out.println("channelUnregistered " + id);
ctx.fireChannelUnregistered();
}
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
System.out.println("channelActive " + id);
ctx.fireChannelActive();
}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
System.out.println("channelInactive " + id);
ctx.fireChannelInactive();
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
System.out.println("channelRead " + id);
ctx.fireChannelRead(msg);
//ctx.channel().pipeline().fireChannelRead(msg);
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
System.out.println("channelReadComplete " + id);
ctx.fireChannelReadComplete();
}
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
System.out.println("userEventTriggered " + id);
}
@Override
public void channelWritabilityChanged(ChannelHandlerContext ctx) throws Exception {
System.out.println("channelWritabilityChanged " + id);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
System.out.println("exceptionCaught " + id);
}
}
\ No newline at end of file
package com.kwan.shuyu.old;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
/**
* @author : kwan
* @date : 2021/10/13
* @desc : BIO 存在C10k挑战
*/
public class BIOServer {
public static void start(int port) throws IOException {
//ServerSocket
ServerSocket serverSocket = new ServerSocket();
//bind & listen
serverSocket.bind(new InetSocketAddress(port), 2);//backlog, accept queue was created in listen()
while (true) {
//accept
final Socket clientSocket = serverSocket.accept();//block
System.out.println("accept!");
new Thread(() -> {// or user thread pool
try {
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
String line = in.readLine();//block
while (line != null) {
out.println(line);
out.flush();
line = in.readLine();//block
}
clientSocket.close();
} catch (IOException e) {
e.printStackTrace();
try {
clientSocket.close();
} catch (IOException ee) {
e.printStackTrace();
}
}
}).start();
}
}
public static void main(String[] args) throws InterruptedException, IOException {
start(8084);
}
}
\ No newline at end of file
package com.kwan.shuyu.old;
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 NIOServer {
public static void start(int port) throws IOException {
ServerSocketChannel serverChannel = ServerSocketChannel.open();
serverChannel.configureBlocking(false);//nonblocking
InetSocketAddress address = new InetSocketAddress(port);
//bind & listen
serverChannel.bind(address);
Selector selector = Selector.open();
serverChannel.register(selector, SelectionKey.OP_ACCEPT);
while (true) {
selector.select();//scan
Set<SelectionKey> readyKeys = selector.selectedKeys();
Iterator<SelectionKey> it = readyKeys.iterator();
while (it.hasNext()) {
SelectionKey key = it.next();
//accept
if (key.isAcceptable()) {
ServerSocketChannel server = (ServerSocketChannel) key.channel();
SocketChannel socket = server.accept();
System.out.println("Accept !");
socket.configureBlocking(false);//don't forget to set nonblocking
socket.register(selector, SelectionKey.OP_READ);//tricky
}
if (key.isReadable()) {
SocketChannel socket = (SocketChannel) key.channel();
final ByteBuffer buffer = ByteBuffer.allocate(64);
final int bytesRead = socket.read(buffer);//also nonblock, how to convert byte to frame
if (bytesRead > 0) {
buffer.flip();
int ret = socket.write(buffer);
if (ret <= 0) {
//register op_write
socket.register(selector, SelectionKey.OP_WRITE);
}
buffer.clear();
} else if (bytesRead < 0) {//means connection closed
key.cancel();
socket.close();
System.out.println("Client close");
}
}
// if (key.isWritable()) {
// SocketChannel socket = (SocketChannel) key.channel();
// final ByteBuffer buffer = ByteBuffer.allocate(64);
// socket.write(buffer);
// //remove
// }
it.remove();//don't forget, why need to manually move?
}
}
}
public static void main(String[] args) throws InterruptedException, IOException {
start(8084);
}
}
\ No newline at end of file
package com.kwan.shuyu.old;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
public class OIOClient {
public static final String[] commands = new String[]{
"hi",
"i am client",
"helloworld",
"java and netty"
};
public static void main(String[] args) throws IOException {
int concurrent = 1;
Runnable task = () -> {
try {
Socket socket = new Socket("127.0.0.1", 8084);
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
/**
* HEADER(2)|LENGTH(2)|BODY
* LENGTH = (self(2) + BODY), not include header
*/
for (String str : commands) {
out.writeByte('A');
out.writeByte('W');
int length = str.length();
out.writeShort(length * 2 + 2);//why *2 here?
out.writeChars(str);
}
out.flush();
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String line = null;
while (!((line = br.readLine()) == null)) {
System.out.println(line);
}
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
};
for (int i = 0; i < concurrent; i++) {
new Thread(task).start();
}
}
}
\ No newline at end of file
package com.kwan.shuyu.old;
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 Reactor {
interface ChannelHandler {
void onRead(SocketChannel channel) throws Exception;
void onAccept();
}
private static ChannelHandler echo = new ChannelHandler() {
@Override
public void onRead(SocketChannel socket) throws IOException {
final ByteBuffer buffer = ByteBuffer.allocate(256);
final int bytesRead = socket.read(buffer);
if (bytesRead > 0) {
buffer.flip();
socket.write(buffer);
buffer.clear();
} else if (bytesRead < 0) {
socket.close();
System.out.println("Client close");
}
}
@Override
public void onAccept() {
}
};
public static void start(int port) throws Exception {
final ServerSocketChannel serverChannel = ServerSocketChannel.open();
serverChannel.configureBlocking(false);
InetSocketAddress address = new InetSocketAddress(port);
//bind & listen
serverChannel.bind(address);
final Selector selector = Selector.open();
SelectionKey sk = serverChannel.register(selector, SelectionKey.OP_ACCEPT);
sk.attach(new ChannelHandler() {//Acceptor
@Override
public void onRead(SocketChannel channel) {
}
@Override
public void onAccept() {
try {
SocketChannel socket = serverChannel.accept();
System.out.println("Accept !");
socket.configureBlocking(false);
SelectionKey sk = socket.register(selector, 0);//register op_read here is also ok in single thread
sk.attach(echo);
sk.interestOps(SelectionKey.OP_READ);
} catch (IOException e) {
e.printStackTrace();
}
}
});
while (true) {
selector.select();
Set<SelectionKey> readyKeys = selector.selectedKeys();
Iterator<SelectionKey> it = readyKeys.iterator();
while (it.hasNext()) {
SelectionKey key = it.next();
ChannelHandler handler = (ChannelHandler) key.attachment();
//accept
if (key.isAcceptable()) {
handler.onAccept();
}
if (key.isReadable()) {
handler.onRead((SocketChannel) key.channel());
}
it.remove();//don't forget
}
}
}
public static void main(String[] args) throws Exception {
start(8084);
}
}
\ No newline at end of file
package com.kwan.shuyu.until;
import io.netty.util.internal.StringUtil;
import java.nio.ByteBuffer;
import static io.netty.util.internal.MathUtil.isOutOfBounds;
/**
* ByteBuffer工具类
*
* @author : qinyingjie
* @version : 2.2.0
* @date : 2023/4/18 17:43
*/
public class ByteBufferUtil {
private static final char[] BYTE2CHAR = new char[256];
private static final char[] HEXDUMP_TABLE = new char[256 * 4];
private static final String[] HEXPADDING = new String[16];
private static final String[] HEXDUMP_ROWPREFIXES = new String[65536 >>> 4];
private static final String[] BYTE2HEX = new String[256];
private static final String[] BYTEPADDING = new String[16];
static {
final char[] DIGITS = "0123456789abcdef".toCharArray();
for (int i = 0; i < 256; i++) {
HEXDUMP_TABLE[i << 1] = DIGITS[i >>> 4 & 0x0F];
HEXDUMP_TABLE[(i << 1) + 1] = DIGITS[i & 0x0F];
}
int i;
// Generate the lookup table for hex dump paddings
for (i = 0; i < HEXPADDING.length; i++) {
int padding = HEXPADDING.length - i;
StringBuilder buf = new StringBuilder(padding * 3);
for (int j = 0; j < padding; j++) {
buf.append(" ");
}
HEXPADDING[i] = buf.toString();
}
// Generate the lookup table for the start-offset header in each row (up to 64KiB).
for (i = 0; i < HEXDUMP_ROWPREFIXES.length; i++) {
StringBuilder buf = new StringBuilder(12);
buf.append( "\r\n");
buf.append(Long.toHexString(i << 4 & 0xFFFFFFFFL | 0x100000000L));
buf.setCharAt(buf.length() - 9, '|');
buf.append('|');
HEXDUMP_ROWPREFIXES[i] = buf.toString();
}
// Generate the lookup table for byte-to-hex-dump conversion
for (i = 0; i < BYTE2HEX.length; i++) {
BYTE2HEX[i] = ' ' + StringUtil.byteToHexStringPadded(i);
}
// Generate the lookup table for byte dump paddings
for (i = 0; i < BYTEPADDING.length; i++) {
int padding = BYTEPADDING.length - i;
StringBuilder buf = new StringBuilder(padding);
for (int j = 0; j < padding; j++) {
buf.append(' ');
}
BYTEPADDING[i] = buf.toString();
}
// Generate the lookup table for byte-to-char conversion
for (i = 0; i < BYTE2CHAR.length; i++) {
if (i <= 0x1f || i >= 0x7f) {
BYTE2CHAR[i] = '.';
} else {
BYTE2CHAR[i] = (char) i;
}
}
}
/**
* 打印所有内容
*
* @param buffer
*/
public static void debugAll(ByteBuffer buffer) {
int oldlimit = buffer.limit();
buffer.limit(buffer.capacity());
StringBuilder origin = new StringBuilder(256);
appendPrettyHexDump(origin, buffer, 0, buffer.capacity());
System.out.println("+--------+-------------------- all ------------------------+----------------+");
System.out.printf("position: [%d], limit: [%d]\n", buffer.position(), oldlimit);
System.out.println(origin);
buffer.limit(oldlimit);
}
/**
* 打印可读取内容
*
* @param buffer
*/
public static void debugRead(ByteBuffer buffer) {
StringBuilder builder = new StringBuilder(256);
appendPrettyHexDump(builder, buffer, buffer.position(), buffer.limit() - buffer.position());
System.out.println("+--------+-------------------- read -----------------------+----------------+");
System.out.printf("position: [%d], limit: [%d]\n", buffer.position(), buffer.limit());
System.out.println(builder);
}
private static void appendPrettyHexDump(StringBuilder dump, ByteBuffer buf, int offset, int length) {
if (isOutOfBounds(offset, length, buf.capacity())) {
throw new IndexOutOfBoundsException(
"expected: " + "0 <= offset(" + offset + ") <= offset + length(" + length
+ ") <= " + "buf.capacity(" + buf.capacity() + ')');
}
if (length == 0) {
return;
}
dump.append(
" +-------------------------------------------------+" +
"\r\n" + " | 0 1 2 3 4 5 6 7 8 9 a b c d e f |" +
"\r\n" + "+--------+-------------------------------------------------+----------------+");
final int startIndex = offset;
final int fullRows = length >>> 4;
final int remainder = length & 0xF;
// Dump the rows which have 16 bytes.
for (int row = 0; row < fullRows; row++) {
int rowStartIndex = (row << 4) + startIndex;
// Per-row prefix.
appendHexDumpRowPrefix(dump, row, rowStartIndex);
// Hex dump
int rowEndIndex = rowStartIndex + 16;
for (int j = rowStartIndex; j < rowEndIndex; j++) {
dump.append(BYTE2HEX[getUnsignedByte(buf, j)]);
}
dump.append(" |");
// ASCII dump
for (int j = rowStartIndex; j < rowEndIndex; j++) {
dump.append(BYTE2CHAR[getUnsignedByte(buf, j)]);
}
dump.append('|');
}
// Dump the last row which has less than 16 bytes.
if (remainder != 0) {
int rowStartIndex = (fullRows << 4) + startIndex;
appendHexDumpRowPrefix(dump, fullRows, rowStartIndex);
// Hex dump
int rowEndIndex = rowStartIndex + remainder;
for (int j = rowStartIndex; j < rowEndIndex; j++) {
dump.append(BYTE2HEX[getUnsignedByte(buf, j)]);
}
dump.append(HEXPADDING[remainder]);
dump.append(" |");
// Ascii dump
for (int j = rowStartIndex; j < rowEndIndex; j++) {
dump.append(BYTE2CHAR[getUnsignedByte(buf, j)]);
}
dump.append(BYTEPADDING[remainder]);
dump.append('|');
}
dump.append( "\r\n" +
"+--------+-------------------------------------------------+----------------+");
}
private static void appendHexDumpRowPrefix(StringBuilder dump, int row, int rowStartIndex) {
if (row < HEXDUMP_ROWPREFIXES.length) {
dump.append(HEXDUMP_ROWPREFIXES[row]);
} else {
dump.append( "\r\n");
dump.append(Long.toHexString(rowStartIndex & 0xFFFFFFFFL | 0x100000000L));
dump.setCharAt(dump.length() - 9, '|');
dump.append('|');
}
}
public static short getUnsignedByte(ByteBuffer buffer, int index) {
return (short) (buffer.get(index) & 0xFF);
}
}
\ No newline at end of file
helloworld秦书予
\ No newline at end of file
helloworld秦书予
\ No newline at end of file
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册