
正文
javanio实例代码 java nil
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
用Nio技术实现c/s结构程序
服务端程序:
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
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.Enumeration;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Set;
public class NioServer {
public static final int SERVERPORT=5555;
public static final String[] USERNAME={"1","2","3","4","5","jack","tom"};
public static final String PASSWORD="1";
public static final String ISACK="ACK";
public static final String ISNAK="NAK!";
// Selector selector;//选择器
// SelectionKey key;//key。 一个key代表一个Selector 在NIO通道上的注册,类似主键;
// //取得这个Key后就可以对Selector在通道上进行操作
private ByteBuffer echoBuffer = ByteBuffer.allocate( 1024 );// 通道数据缓冲区
public NioServer(){
}
public static void main(String[] args) throws IOException {
NioServer ns=new NioServer();
ns.BuildNioServer();
}
public void BuildNioServer() throws IOException{
/////////////////////////////////////////////////////////
///////先对服务端的ServerSocket进行注册,注册到Selector ////
/////////////////////////////////////////////////////////
ServerSocketChannel ssc = ServerSocketChannel.open();//新建NIO通道
ssc.configureBlocking( false );//使通道为非阻塞
ServerSocket ss = ssc.socket();//创建基于NIO通道的socket连接
//新建socket通道的端口
ss.bind(new InetSocketAddress("127.0.0.1",SERVERPORT));
Selector selector=Selector.open();//获取一个选择器
//将NIO通道选绑定到择器,当然绑定后分配的主键为skey
//SelectionKey skey =
ssc.register( selector, SelectionKey.OP_ACCEPT );
////////////////////////////////////////////////////////////////////
//// 接收客户端的连接Socket,并将此Socket也接连注册到Selector ////
///////////////////////////////////////////////////////////////////
while(true){
int num = selector.select();//获取通道内是否有选择器的关心事件
if(num1){continue; }
Set selectedKeys = selector.selectedKeys();//获取通道内关心事件的集合
Iterator it = selectedKeys.iterator();
while (it.hasNext()) {//遍历每个事件
try{
SelectionKey key = (SelectionKey)it.next();
//有一个新联接接入事件,服务端事件
if ((key.readyOps() SelectionKey.OP_ACCEPT)
== SelectionKey.OP_ACCEPT) {
// 接收这个新连接
ServerSocketChannel serverChanel = (ServerSocketChannel)key.channel();
//从serverSocketChannel中创建出与客户端的连接socketChannel
SocketChannel sc = serverChanel.accept();
sc.configureBlocking( false );
// Add the new connection to the selector
// 把新连接注册到选择器
//SelectionKey newKey =
sc.register( selector, SelectionKey.OP_READ );
it.remove();
System.out.println( "Got connection from "+sc );
}else
//读客户端数据的事件,此时有客户端发数据过来,客户端事件
if((key.readyOps() SelectionKey.OP_READ)
== SelectionKey.OP_READ){
// 读取数据
SocketChannel sc = (SocketChannel)key.channel();
while(sc.read(echoBuffer) 0){ ;}
echoBuffer.flip();
byte [] content = new byte[echoBuffer.limit()];
echoBuffer.get(content);
String result=new String(content);
doPost(result,sc);
echoBuffer.clear();
it.remove();
}
}catch(Exception e){}
}
}
}
Hashtable table=new Hashtable();
public void doPost(String str,SocketChannel sc){
boolean isok=false;
int index=str.indexOf('|');
if(index=0){ //index0 有"|"符号,代表登陆,没有表示普通聊天
String name=str.substring(0,index);
String pswd=str.substring(index+1);
if(pswd==null){pswd="";}
if(name!=null){
if(pswd.equals(PASSWORD) ){
isok=false;
for(int i=0;iUSERNAME.length;i++){
if(USERNAME[i].equals(name)){
isok=true;
break;
}
}
}else{
isok=false;
}
}else{
isok=false;
}
String result="";
if(isok){
result="ACK";
//加入到用户通道列表中
User user=new User();
user.password=pswd;
user.name=name;
user.sc=sc;
table.put(user.name, user);
}else{
result="NAK!";
}
ByteBuffer bb = ByteBuffer.allocate( result.length() );
bb.put(result.getBytes());
bb.flip();
try {
sc.write(bb);
} catch (IOException e) {
e.printStackTrace();
}
bb.clear();
}else{ //普通聊天
//遍历所有己注册通道,向所有人发消息(包括发送者自己)
System.out.println("通道数:"+table.size());
Enumeration en=table.elements();
while(en.hasMoreElements()){
User user=(User)en.nextElement();
SocketChannel channel=user.sc;
if(user!=null channel!=null channel.isConnected()){
System.out.println("发送:str"+str);
ByteBuffer bb = ByteBuffer.allocate( str.length() );
bb.put(str.getBytes());
bb.flip();
try {
channel.write(bb);
} catch (IOException e) {
e.printStackTrace();
}
bb.clear();
}else{
if(user!=null user.name!=null){
table.remove(user.name);
}
}
}
}
}
public class User{
public String name="";
public String password="";
public boolean isLogin=false;
public SocketChannel sc=null;
}
}
客户端:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class UserClient implements ActionListener{
JFrame jf;
JPanel jp;
JLabel label_name;
JLabel label_pswd;
JTextField userName;
JButton jb;
JPasswordField paswrd;
JLabel hintStr;
public UserClient (){
jf=new JFrame("XXX 登陆系统");
jp=new JPanel();
jf.setContentPane(jp);
jf.setPreferredSize(new Dimension(350,220));
jp.setPreferredSize(new Dimension(350,220));
jp.setBackground(Color.gray);
label_name=new JLabel();
label_name.setPreferredSize(new Dimension(150,30));
label_name.setText("请输入帐户(数字或英文):");
userName=new JTextField();
userName.setPreferredSize(new Dimension(150,30));
jp.add(label_name);
jp.add(userName);
label_pswd=new JLabel();
label_pswd.setPreferredSize(new Dimension(150,30));
label_pswd.setText("请输入密码:");
jp.add(label_pswd);
paswrd=new JPasswordField();
paswrd.setPreferredSize(new Dimension(150,30));
jp.add(paswrd);
jb=new JButton("OK");
jb.setPreferredSize(new Dimension(150,30));
jb.setText("确 定");
jb.addActionListener( this);
jp.add(jb);
hintStr=new JLabel();
hintStr.setPreferredSize(new Dimension(210,40));
hintStr.setText("");
hintStr.setForeground(Color.RED);
jp.add(hintStr);
jf.pack();
jf.setVisible(true);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private String name;
private String pswd;
public void actionPerformed(ActionEvent e) {
if(e.getSource()==jb){
name=userName.getText().trim();
pswd=new String(paswrd.getPassword());
if(pswd==null){
pswd="";
}else{
pswd=pswd.trim();
}
if(name!=null name.length()0){
hintStr.setText("正在验证客户端,请稍候...");
start();
}
}else
if(e.getSource()==clear){//清屏
text.setText("");
}else
if(e.getSource()==send){//发送
String msg=this.jtf.getText();
if(msg!=null){
if(msg.trim().length()0){
msg=" "+name+" said:"+msg+"\r\n";
sendMessage(msg);
jtf.setText("");
}
}
}
}
OutputStream os;
Socket s;
InputStream is;
public void start(){
//建立联网线程
new Thread(new Runnable(){
public void run() {
try {
s=new Socket("127.0.0.1",5555);
//写
os=s.getOutputStream();
os.write(name.getBytes());
os.write('|');//用户名与密码用"|"分隔
os.write(pswd.getBytes());
os.flush();
//读内容
Thread.sleep(1000);
is=s.getInputStream();
int len=is.available();
System.out.println("len:"+len);
byte[] bytes=new byte[len];
is.read(bytes);
String resut=new String(bytes);
System.out.println("resut:"+resut);
if(resut.equals("ACK")){
hintStr.setText("验证成功,欢迎光临!");
//TODO 这里通过返回结果处理
handleLoginResult();
}else{
paswrd.setText(null);
hintStr.setText("用户名或密码错误,请重新输入");
}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}finally{
}
}
}).start();
}
////////////////////////////////////////////////////////////////////
//处理登陆结果,出新界面
//登陆后新界面的元素组件定义在这里,注意,
//现在随便弄的,你要改漂亮些
////////////////////////////////////////////////////////////////////
JTextArea text;
JButton send;
JButton clear;
JTextArea jtf;
public void handleLoginResult(){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
this.jp.removeAll();//清空所有组件;
jf.setSize(800,600);
jp.setSize(800,600);
jf.setPreferredSize(new Dimension(800,600));
jp.setPreferredSize(new Dimension(800,600));
//加聊天内容框
text=new JTextArea();
text.setBackground(Color.WHITE);
text.setForeground(Color.BLUE);
text.setPreferredSize(new Dimension(750,450));
jp.add(text);
//加发送内容框
jtf=new JTextArea();
jtf.setPreferredSize(new Dimension(750,50));
jp.add(jtf);
//加按钮
send=new JButton("发送");
clear=new JButton("清屏");
send.setPreferredSize(new Dimension(100,30));
clear.setPreferredSize(new Dimension(100,30));
jp.add(send);
jp.add(clear);
send.addActionListener(this);
clear.addActionListener(this);
jf.pack();
jf.repaint();
//开始读线程
readMessage();
}
//////////////////////////////////////////////////////
//发送消息线程
//////////////////////////////////////////////////////
public void sendMessage(String msg){
final String toSend=msg;
new Thread(
new Runnable(){
public void run(){
if(s==null ){
return;
}
//写
try {
System.out.println("发送:"+toSend);
os.write(toSend.getBytes());
os.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}
).start();
}
/////////////////////////////////////////////////////////
//读取线程,死循环,不停读取
public boolean isRunning=true;
public void readMessage( ){
new Thread(
new Runnable(){
public void run(){
while(isRunning){
if(s==null ){
return;
}
try {
InputStream is=s.getInputStream();
int len=is.available();
//System.out.println("len:"+len);
byte[] bytes=new byte[len];
is.read(bytes);
String resut=new String(bytes);
//System.out.println("resut:"+resut);
if(resut!=null resut.length()0){
System.out.println("收到!!!resut:"+resut);
text.append(resut);
}
} catch (IOException e) {
e.printStackTrace();
}
//睡眠2秒
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
).start();
}
public static void main(String[] args) {
new UserClient();
}
}
相关问答
Q1: 怎么为JAVA NIO或Netty程序设置网络通信代理?
服务端
// 设置一个处理客户端消息和各种消息事件的类(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()); }});
要传递对象javanio实例代码,自然要有一个被传递模型,一个简单的Pojo,当然,实现序列化接口是必须的。
/** * @author lihzh * @alia OneCoder * @blog */public class Command implementsSerializable { privatestaticfinallongserialVersionUID = 7590999461767050471L; privateString actionName; publicString getActionName() { returnactionName; } publicvoidsetActionName(String actionName) { this.actionName = actionName; }}
服务端和客户端里,我们自定义的Handler实现如下:
ObjectServerHandler .java
/** * 对象传递服务端代码 * * @author lihzh * @alia OneCoder * @blog */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 * @blog */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是有顺序的,如果javanio实例代码你颠倒一下注册顺序:
bootstrap.setPipelineFactory(newChannelPipelineFactory() {
@Override publicChannelPipeline getPipeline()throwsException { returnChannels.pipeline(newObjectServerHandler(), newObjectDecoder(ClassResolvers.cacheDisabled(this .getClass().getClassLoader())) ); }});
结果就是,会先进入我们自己的业务,再进行解码。这自然是不行的,会强转失败。至此,你应该会用Netty传递对象了吧。
Q2: 如何引入java.nio.heapbytebuffer
heap buffer 和 direct buffer区别
在Java的NIO中,我们一般采用ByteBuffer缓冲区来传输数据,一般情况下我们创建Buffer对象是通过ByteBuffer的两个静态方法:
ByteBuffer.allocate(int capacity);
ByteBuffer.wrap(byte[] array);
查看JDK的NIO的源代码关于这两个部分:
/**allocate()函数的源码**/
public static ByteBuffer allocate(int capacity) {
if (capacity 0)
throw new IllegalArgumentException();
return new HeapByteBuffer(capacity, capacity);
}
/**wrap()函数的源码**/
public static ByteBuffer wrap(byte[] array) {
return wrap(array, 0, array.length);
}
//
public static ByteBuffer wrap(byte[] array,
int offset, int length)
{
try {
return new HeapByteBuffer(array, offset, length);
} catch (IllegalArgumentException x) {
throw new IndexOutOfBoundsException();
}
}
我们可以很清楚的发现,这两个方法都是实例化HeapByteBuffer来创建的ByteBuffer对象,也就是heap buffer. 其实除了heap buffer以外还有一种buffer,叫做direct buffer。我们也可以创建这一种buffer,通过ByteBuffer.allocateDirect(int capacity)方法,查看JDK源码如下:
public static ByteBuffer allocateDirect(int capacity) {
return new DirectByteBuffer(capacity);
}
我们发现该函数调用的是DirectByteBuffer(capacity)这个类,这个类就是创建了direct buffer。
Q3: 怎么用java代码调用远程Linux上的shell脚本
package org.shirdrn.shell;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
/**
* 远程Shell脚本执行工具
*
* @author Administrator
*/
public class RemoteShellTool {
private Connection conn;
private String ipAddr;
private String charset = Charset.defaultCharset().toString();
private String userName;
private String password;
public RemoteShellTool(String ipAddr, String userName, String password, String charset) {
this.ipAddr = ipAddr;
this.userName = userName;
this.password = password;
if(charset != null) {
this.charset = charset;
}
}
/**
* 登录远程Linux主机
*
* @return
* @throws IOException
*/
public boolean login() throws IOException {
conn = new Connection(ipAddr);
conn.connect(); // 连接
return conn.authenticateWithPassword(userName, password); // 认证
}
/**
* 执行Shell脚本或命令
*
* @param cmds 命令行序列
* @return
*/
public String exec(String cmds) {
InputStream in = null;
String result = "";
try {
if (this.login()) {
Session session = conn.openSession(); // 打开一个会话
session.execCommand(cmds);
in = session.getStdout();
result = this.processStdout(in, this.charset);
conn.close();
}
} catch (IOException e1) {
e1.printStackTrace();
}
return result;
}
/**
* 解析流获取字符串信息
*
* @param in 输入流对象
* @param charset 字符集
* @return
*/
public String processStdout(InputStream in, String charset) {
byte[] buf = new byte[1024];
StringBuffer sb = new StringBuffer();
try {
while (in.read(buf) != -1) {
sb.append(new String(buf, charset));
}
} catch (IOException e) {
e.printStackTrace();
}
return sb.toString();
}
}
Q4: 介绍一下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();
}
}
Q5: JAVA用nio写CS程序,服务器端接收到的信息不完整,求助!SocketChannel,Bytebuffer
while(true){
buff.clear();
int len = sc.read(buff);
if(len ==-1){ break;}
buff.flip();
content += charset.decode(buff);
}
关于javanio实例代码和java nil的介绍到此就结束了,不知道你从中找到你需要的信息了吗 ?如果你还想了解更多这方面的信息,记得收藏关注本站。






