javanio完整代码 java代码例子讲解
java nio 非阻塞读写具体应该怎么操作,能否给个例子程序
package com.java.xiong.Net17;
十余年的禹州网站建设经验,针对设计、前端、开发、售后、文案、推广等六对一服务,响应快,48小时及时工作处理。营销型网站的优势是能够根据用户设备显示端的尺寸不同,自动调整禹州建站的显示方式,使网站能够适用不同显示终端,在浏览器中调整网站的宽度,无论在任何一种浏览器上浏览网站,都能展现优雅布局与设计,从而大程度地提升浏览体验。创新互联建站从事“禹州网站设计”,“禹州网站推广”以来,每个客户项目都认真落实执行。
import java.io.IOException;
import java点虐 .InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.Channel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
public class NServer {
// 用于检测所有的Channel状态的selector
private Selector selector = null;
static final int PORT = 30000;
// 定义实现编码、解码的字符串集对象
private Charset charse = Charset.forName("GBK");
public void init() throws IOException {
selector = Selector.open();
// 通过open方法来打开一个未绑定的ServerSocketChannel是咧
ServerSocketChannel server = ServerSocketChannel.open();
InetSocketAddress isa = new InetSocketAddress("127.0.0.1", PORT);
// 将该ServerSocketChannel绑定到指定的IP地址
server.bind(isa);
// 设置serverSocket已非阻塞方式工作
server.configureBlocking(false);
// 将server注册到指定的selector对象
server.register(selector, SelectionKey.OP_ACCEPT);
while (selector.select() 0) {
// 一次处理selector上的每个选择的SelectionKey
for (SelectionKey sk : selector.selectedKeys()) {
// 从selector上已选择的Kye集中删除正在处理的SelectionKey
selector.selectedKeys().remove(sk);
// 如果sk对应的Channel包含客户端的连接请求
if (sk.isAcceptable()) {
// 调用accept方法接收连接,产生服务器段的SocketChennal
SocketChannel sc = server.accept();
// 设置采用非阻塞模式
sc.configureBlocking(false);
// 将该SocketChannel注册到selector
sc.register(selector, SelectionKey.OP_READ);
}
// 如果sk对应的Channel有数据需要读取
if (sk.isReadable()) {
// 获取该SelectionKey对银行的Channel,该Channel中有刻度的数据
SocketChannel sc = (SocketChannel) sk.channel();
// 定义备注执行读取数据源的ByteBuffer
ByteBuffer buff = ByteBuffer.allocate(1024);
String content = "";
// 开始读取数据
try {
while (sc.read(buff) 0) {
buff.flip();
content += charse.decode(buff);
}
System.out.println("读取的数据:" + content);
// 将sk对应的Channel设置成准备下一次读取
sk.interestOps(SelectionKey.OP_READ);
}
// 如果捕获到该sk对银行的Channel出现了异常,表明
// Channel对应的Client出现了问题,所以从Selector中取消
catch (IOException io) {
// 从Selector中删除指定的SelectionKey
sk.cancel();
if (sk.channel() != null) {
sk.channel().close();
}
}
// 如果content的长度大于0,则连天信息不为空
if (content.length() 0) {
// 遍历selector里注册的所有SelectionKey
for (SelectionKey key : selector.keys()) {
// 获取该key对应的Channel
Channel targerChannel = key.channel();
// 如果该Channel是SocketChannel对象
if (targerChannel instanceof SocketChannel) {
// 将读取到的内容写入该Channel中
SocketChannel dest = (SocketChannel) targerChannel;
dest.write(charse.encode(content));
}
}
}
}
}
}
}
public static void main(String [] args) throws IOException{
new NServer().init();
}
}
JAVA用nio写CS程序,服务器端接收到的信息不完整,求助!SocketChannel,Bytebuffer
while(true){
buff.clear();
int len = sc.read(buff);
if(len ==-1){ break;}
buff.flip();
content += charset.decode(buff);
}
介绍一下Java NIO,NIO读取文件都有哪些方法
NIO也就是New I/O,是一组扩展Java IO操作的API集, 于Java 1.4起被引入,Java 7中NIO又提供了一些新的文件系统API,叫NIO2.
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网络编程的小例子,要求客户端一直与服务器保持连接
import java.awt.*;
import java.awt.event.*;
import java.io.IOException;
import java点虐 .*;
import java.io.*;
public class chatClient extends Frame {
/**
* @param args
*/
TextField tfTxT=new TextField();
TextArea taContent=new TextArea();
Socket s=null;
DataOutputStream dos=null;
DataInputStream dis=null;
private boolean bConnected =false;
public static void main(String[] args) {
new chatClient().lunachFrame();
}
private class RecvThread implements Runnable{
public void run() {
try{
while(bConnected){
String str=dis.readUTF();
taContent.setText(taContent.getText()+str+'\n');
}
}catch(IOException e){
e.printStackTrace();
}
}
}
public void lunachFrame(){
this.setLocation(400, 300);
this.setSize(300,300);
//this.setLayout(new FlowLayout());
this.add(tfTxT,"South");
this.add(taContent,"North");
pack();
tfTxT.addActionListener(new TFListener());
this.addWindowListener(new WindowClose());
this.setVisible(true);
connect();
new Thread(new RecvThread()).start();
}
public void connect(){
try {
s= new Socket("127.0.0.1",8888);
dos =new DataOutputStream(s.getOutputStream());
dis =new DataInputStream(s.getInputStream());
System.out.println("connected!");
bConnected=true;
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void disconnect(){
try {
dos.close();
s.close();
} catch (Exception e) {
// TODO 自动生成 catch 块
e.printStackTrace();
}
}
class WindowClose extends WindowAdapter{
@Override
public void windowClosing(WindowEvent e) {
// TODO 自动生成方法存根
System.exit(0);
disconnect();
}
}
private class TFListener implements ActionListener{
public void actionPerformed(ActionEvent e) {
String str=tfTxT.getText().trim();//trim去掉两边空格
//taContent.setText(str);
tfTxT.setText("");
try {
dos.writeUTF(str);
dos.flush();
//dos.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
======================================
import java.io.IOException;
import java点虐 .*;
import java.io.*;
import java.util.*;
public class ChatServer {
ListClient clients=new ArrayListClient();
Client c=null;
public static void main(String[] args){
new ChatServer().start();
}
public void start(){
boolean started=false;
ServerSocket ss=null;
DataInputStream dis=null;
try{
ss=new ServerSocket(8888);
started =true;
}catch(Exception e)
{
e.printStackTrace();
}
try{
while(started){
Socket s=ss.accept();
c=new Client(s);//启动线程,实行run()方法
System.out.println("a client connected!");
new Thread(c).start();//启动start方法,循环.start是Thread中的方法与这上面的start无关
clients.add(c);
//dis.close();
}
} catch (Exception e) {
//e.printStackTrace();
}
finally{
try {
ss.close();
} catch (IOException e) {
// TODO 自动生成 catch 块
e.printStackTrace();
}
}
}
class Client implements Runnable{
private Socket s;
private DataInputStream dis =null;
private boolean bConnected =false;
private DataOutputStream dos=null;
public Client(Socket s){
this.s=s;
try {
dis=new DataInputStream(s.getInputStream());
dos =new DataOutputStream(s.getOutputStream());
bConnected =true;
} catch (IOException e) {
// TODO 自动生成 catch 块
e.printStackTrace();
}
}
public void send(String str)throws Exception{
dos.writeUTF(str);
}
public void run() {
try{
while(bConnected){
String str = dis.readUTF();
System.out.println(str);
for(int i=0;iclients.size();i++){
c=clients.get(i);
c.send(str);
}
/*for(IteratorClient it=clients.iterator();it.hasNext();){
Client c=it.next();
c.send(str);
}*/
}
}catch(SocketException e){
clients.remove(this);
System.out.println("客户下线了");
}
catch(EOFException e){
System.out.println("Client closed");
}
catch (Exception e){
//e.printStackTrace();
}
finally{
try {
if(dis !=null) dis.close();
if(dos !=null) dos.close();
if(s!=null) s.close();
} catch (Exception e1) {
// TODO 自动生成 catch 块
//e1.printStackTrace();
}
}
}
}
}
第一个是客户端,
第二个是server端
新闻标题:javanio完整代码 java代码例子讲解
网站路径:http://myzitong.com/article/ddgggcg.html