① java nio如何设置tcp报文紧急推送
在java中可以基于java.nio.channels中的Channel和Selector的相关类来实现TCP/IP+NIO方式的系统间通信。
用于系统间通信依靠SocketChannel和ServerSocketChannel,SocketChannel用于建立连接,监听事件及操作读写,ServerSocketChannel用于监听端口及监听连接事件,可通过Selector来获取是否有要处理的事件。
服务端
// 设置一个处理客户端消息和各种消息事件的类(Handler)bootstrap.setPipelineFactory(newChannelPipelineFactory() { @Override publicChannelPipeline getPipeline()throwsException { returnChannels.pipeline( newObjectDecoder(ClassResolvers.cacheDisabled(this .getClass().getClassLoader())), newObjectServerHandler()); }});
客户端
// 设置一个处理服务端消息和各种消息事件的类(Handler)
bootstrap.setPipelineFactory(newChannelPipelineFactory() { @Override publicChannelPipeline getPipeline()throwsException { returnChannels.pipeline(newObjectEncoder(), newObjectClientHandler()); }});
要传递对象,自然要有一个被传递模型,一个简单的Pojo,当然,实现序列化接口是必须的。
/** * @author lihzh * @alia OneCoder * @bloghttp://www.coderli.com */public class Command implementsSerializable { = 7590999461767050471L; privateString actionName; publicString getActionName() { returnactionName; } publicvoidsetActionName(String actionName) { this.actionName = actionName; }}
服务端和客户端里,我们自定义的Handler实现如下:
ObjectServerHandler .java
/** * 对象传递服务端代码 * * @author lihzh * @alia OneCoder * @bloghttp://www.coderli.com */public class ObjectServerHandler extendsSimpleChannelHandler { /** * 当接受到消息的时候触发 */ @Override publicvoidmessageReceived(ChannelHandlerContext ctx, MessageEvent e) throwsException { Command command = (Command) e.getMessage(); // 打印看看是不是我们刚才传过来的那个 System.out.println(command.getActionName()); }}
ObjectClientHandler .java
/** * 对象传递,客户端代码 * * @author lihzh * @alia OneCoder * @bloghttp://www.coderli.com */public class ObjectClientHandler extendsSimpleChannelHandler { /** * 当绑定到服务端的时候触发,给服务端发消息。 * * @author lihzh * @alia OneCoder */ @Override publicvoidchannelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) { // 向服务端发送Object信息 sendObject(e.getChannel()); } /** * 发送Object * * @param channel * @author lihzh * @alia OneCoder */ privatevoidsendObject(Channel channel) { Command command =newCommand(); command.setActionName("Hello action."); channel.write(command); } }
启动后,服务端正常打印结果:Hello action.
简单梳理一下思路:
通过Netty传递,都需要基于流,以ChannelBuffer的形式传递。所以,Object -> ChannelBuffer.
Netty提供了转换工具,需要我们配置到Handler。
样例从客户端 -> 服务端,单向发消息,所以在客户端配置了编码,服务端解码。如果双向收发,则需要全部配置Encoder和Decoder。
这里需要注意,注册到Server的Handler是有顺序的,如果你颠倒一下注册顺序:
bootstrap.setPipelineFactory(newChannelPipelineFactory() {
@Override publicChannelPipeline getPipeline()throwsException { returnChannels.pipeline(newObjectServerHandler(), newObjectDecoder(ClassResolvers.cacheDisabled(this .getClass().getClassLoader())) ); }});
结果就是,会先进入我们自己的业务,再进行解码。这自然是不行的,会强转失败。至此,你应该会用Netty传递对象了吧。
③ java基础入门教程都有哪些
网上教程挺多的,刚刚看了一个九天的Java学习入门教程,通过《学生管理系统》案例整合基础知识,巩固加深知识理解。
学习内容:
第一阶段:Java基础语法
Java背景与环境搭建;常量、变量、数据类型;运算符;分支语句;循环语句;数组;方法;二维数组
第二阶段:面向对象基础
面向对象思想理解;类和对象的关系;对象的使用;对象内存图;this关键字;封装;构造方法;JavaBean类的编写
第三阶段:常用API
API手册的使用;String类的特点;不同方式创建String对象的区别;字符串常见面试题;字符串常用方法;StringBuilder类的使用;StringBuilder常用方法;String和StringBuilder的区别对比
第四阶段:集合框架
集合和数组的对比;ArrayList集合对象的使用;ArrayList集合对象常用方法;ArrayList集合遍历,与封装数据到集合;综合案例 - 学生管理系统
网页链接 912t
④ 自学Java怎么入门
自学Java看这一篇就够啦!Java学习路线图分享给你,跟着学习吧!
一、Java基础
⑤ 介绍一下Java NIO,NIO读取文件都有哪些方法
NIO也就是New I/O,是一组扩展Java IO操作的API集, 于Java 1.4起被引入,Java 7中NIO又提供了一些新的文件系统API,叫.
NIO2提供两种主要的文件读取方法:
使用buffer和channel类
使用Path 和 File 类
NIO读取文件有以下三种方式:
1. 旧的NIO方式,使用BufferedReader
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class WithoutNIOExample
{
public static void main(String[] args)
{
BufferedReader br = null;
String sCurrentLine = null;
try
{
br = new BufferedReader(
new FileReader("test.txt"));
while ((sCurrentLine = br.readLine()) != null)
{
System.out.println(sCurrentLine);
}
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
try
{
if (br != null)
br.close();
} catch (IOException ex)
{
ex.printStackTrace();
}
}
}
}
2. 使用buffer读取小文件
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class ReadFileWithFileSizeBuffer
{
public static void main(String args[])
{
try
{
RandomAccessFile aFile = new RandomAccessFile(
"test.txt","r");
FileChannel inChannel = aFile.getChannel();
long fileSize = inChannel.size();
ByteBuffer buffer = ByteBuffer.allocate((int) fileSize);
inChannel.read(buffer);
buffer.rewind();
buffer.flip();
for (int i = 0; i < fileSize; i++)
{
System.out.print((char) buffer.get());
}
inChannel.close();
aFile.close();
}
catch (IOException exc)
{
System.out.println(exc);
System.exit(1);
}
}
}
3. 分块读取大文件
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class ReadFileWithFixedSizeBuffer
{
public static void main(String[] args) throws IOException
{
RandomAccessFile aFile = new RandomAccessFile
("test.txt", "r");
FileChannel inChannel = aFile.getChannel();
ByteBuffer buffer = ByteBuffer.allocate(1024);
while(inChannel.read(buffer) > 0)
{
buffer.flip();
for (int i = 0; i < buffer.limit(); i++)
{
System.out.print((char) buffer.get());
}
buffer.clear(); // do something with the data and clear/compact it.
}
inChannel.close();
aFile.close();
}
}
4. 使用MappedByteBuffer读取文件
import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
public class ReadFileWithMappedByteBuffer
{
public static void main(String[] args) throws IOException
{
RandomAccessFile aFile = new RandomAccessFile
("test.txt", "r");
FileChannel inChannel = aFile.getChannel();
MappedByteBuffer buffer = inChannel.map(FileChannel.MapMode.READ_ONLY, 0, inChannel.size());
buffer.load();?
for (int i = 0; i < buffer.limit(); i++)
{
System.out.print((char) buffer.get());
}
buffer.clear(); // do something with the data and clear/compact it.
inChannel.close();
aFile.close();
}
}
⑥ 如何学习Java的NIO
Java NIO 是一种非阻塞式I/O。
要理解 NIO,要先理解 非阻塞式I/O。
非阻塞式I/O 只是专众多 IO 模型中的一种。
要透切理解 非阻塞式I/O,就属要理解众多 IO 模型的历史和优劣。
要理解为什么会出现 这么多 IO 模型。
就要理解 计算机的 IO 系统和 操作系统如何处理 IO的。
⑦ java学习零基础
对于初学者来说,只要在学习过程中,掌握科学的学习方法,即使零基础的入行者也能充分掌握Java开发技术,那究竟如何才能学习Java呢?
第一阶段:企业入门级项目阶段,可掌握Java核心基础、面向对象、JavaSE API、MySQL数据库、JDBS、HTML+CSS、Servlet、JSP、JavaScript等,可以完成常见中小型互联网项目开发,达到初级Java开发工程师能力。
第二阶段企业框架级项目阶段是进阶阶段,增强Java基础、web基础、CSS/JavaScript进阶、Maven项目管理、Spring5、SpringMVC、Mybatis、SMM综合项目、学员项目等,完成本阶段学员可以胜任各行业企业级项目中高级工程师岗位。
第三阶段亿级大并发分布式项目阶段,掌握Linux、Docker、Vue、SpringBoot、项目整合Vue、分布式项目、Zookeepr、Dubbo、Springcloud、Redis、Elasticsearch、Quartz、RocketMQ、FastDFS、Mycat、CAS、分布式锁、分布式事务、微信开发、学生项目等,学员学完后可以胜任大型、超大型互联网项目开发高级工程师岗位。
初学Java虽然有一定的难度,但Java学习并不是不可逾越,只要你明确方向,找到有效的学习方法,坚持学习,一定能攻克Java难关,成为一名合格的Java开发工程师。如果你是零基础自学,那么所花费的时间与精力是不可估计的。 如果系统学习5个月的时间可以帮助你快速成长。
⑧ JAVA NIO 怎么捕获Socket关闭事件
AVA NIO 如何捕获Socket关闭事件
服务端代码:
Java codeimport java.io.IOException;
import java.net.InetAddress;
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.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;
public class TCP {
ServerSocketChannel socketChannel;
Selector selector;
int port = 8778;
String[] opsName=new String[17];
ByteBuffer buffer;
int count = 0;
public TCP(){
opsName[SelectionKey.OP_ACCEPT]="OP_ACCEPT";
opsName[SelectionKey.OP_CONNECT]="OP_CONNECT";
opsName[SelectionKey.OP_READ]="OP_READ";
opsName[SelectionKey.OP_WRITE]="OP_WRITE";
buffer =ByteBuffer.allocate(10);
try {
socketChannel=ServerSocketChannel.open();
socketChannel.configureBlocking(false);
socketChannel.socket().setReuseAddress(true);
socketChannel.socket().bind(new InetSocketAddress(port));
selector=Selector.open();
System.out.println(socketChannel.hashCode());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void start(){
try {
socketChannel.register(selector, SelectionKey.OP_ACCEPT);
} catch (ClosedChannelException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
System.out.println("server start port "+port);
while(true){
int n;
try {
System.out.print("wait...");
n = selector.select(60000);
System.out.println(n);
if(n<=0)continue;
Iterator<SelectionKey> it = selector.selectedKeys().iterator();
while(it.hasNext()){
SelectionKey key = it.next();
it.remove();
System.out.println("key:"+opsName[key.interestOps()]+","+key.channel().hashCode());
if(key.isReadable()){
System.out.println(key.hashCode()+" isReadable");
socketChannel.accept().register(selector, SelectionKey.OP_READ);
}
else if(key.isAcceptable()){
System.out.println(key.hashCode()+" accepted");
SocketChannel client =socketChannel.accept();
client.configureBlocking(false);
//client.register(selector, SelectionKey.OP_WRITE);
//SocketChannel client =(SocketChannel) key.channel();
buffer.clear();
buffer.putInt(count++);
buffer.flip();
client.write(buffer);
System.out.println(client.hashCode()+" write..");
}
else if(key.isWritable()){
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void main(String[] args) {
TCP tcp = new TCP();
tcp.start();
}
}