上次写了一个socket的基本编程,但是有个问题,阻塞特别严重,于是小编便去找了nio学习了一下...

 public class TimeServer {

     public static void main(String[] args) {
MultipexerTimeServer timersServer=new MultipexerTimeServer("192.168.1.102", 8400);
new Thread(timersServer, "nio-多路复用器").start();
} }
 public class MultipexerTimeServer implements Runnable {

     private Selector selector;

     private ServerSocketChannel serverSocketChannel;

     private volatile boolean stop;

     public MultipexerTimeServer(String addr,int point){
try {
selector=Selector.open();
serverSocketChannel=ServerSocketChannel.open();
serverSocketChannel.socket().bind(new InetSocketAddress(addr, point));
serverSocketChannel.configureBlocking(false);
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
System.out.println("socket服务端:"+serverSocketChannel.socket().getInetAddress()+":"+serverSocketChannel.socket().getLocalPort()+"");
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
} public void stop(){
this.stop=true;
} @Override
public void run() {
while(!stop){
try {
selector.select(1000);
Set<SelectionKey> selectionKeys=selector.selectedKeys();
if(selectionKeys !=null && selectionKeys.size()>0){
Iterator<SelectionKey> it=selectionKeys.iterator();
SelectionKey key=null;
while(it.hasNext()){
key=it.next();
it.remove();
try {
handleInput(key);
} catch (Exception e) {
if(key!=null){
key.cancel();
if(key.channel()!=null){
try {
key.channel().close();
} catch (Exception e1) {
e1.printStackTrace();
}
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
if(selector!=null){
try {
selector.close();
} catch (Exception e) {
e.printStackTrace();
}
}
} private void handleInput(SelectionKey key) throws IOException{
if(key.isValid()){
//处理新接入的请求
if(key.isAcceptable()){
ServerSocketChannel ssc=(ServerSocketChannel)key.channel();
SocketChannel sc=ssc.accept();
sc.configureBlocking(false);
sc.register(selector,SelectionKey.OP_READ);
SocketAddress clientAddress =sc.getRemoteAddress();
System.out.println("socket链接新客户端:" + clientAddress);
}
if(key.isReadable()){
//读取数据
SocketChannel sc=(SocketChannel)key.channel();
ByteBuffer readBuffer=ByteBuffer.allocate(1024);
int readBytes=sc.read(readBuffer);
if(readBytes>0){
readBuffer.flip();
byte[] bytes=new byte[readBuffer.remaining()];
readBuffer.get(bytes);
String body=new String(bytes, Charset.forName("GBK"));
SocketAddress clientAddress =sc.getRemoteAddress();
System.out.println("socket链接老客户端:" + clientAddress);
System.out.println("服务器接收数据:"+body);
//然后回写点数据给客服端
SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String time=dateFormat.format(new Date());
String res="来自与服务端的回应,时间:"+ time;
doWrite(sc,res);
}else if(readBytes<0){
key.cancel();
sc.close();
}else{
//System.out.println("服务器收到0字节数据...");
}
}
}
} private void doWrite(SocketChannel sc,String res) throws IOException{
if(res!=null && res.trim().length()>0){
byte[] bytes=res.getBytes();
ByteBuffer byteBuffer=ByteBuffer.allocate(1024);
byteBuffer.put(bytes);
byteBuffer.flip();
sc.write(byteBuffer);
}
}

代码不想解释太多,有空整理一下nio的基本概念...

java socket nio编程的更多相关文章

  1. Java Socket 网络编程心跳设计概念

    Java Socket 网络编程心跳设计概念   1.一般是用来判断对方(设备,进程或其它网元)是否正常动行,一 般采用定时发送简单的通讯包,如果在指定时间段内未收到对方响应,则判断对方已经当掉.用于 ...

  2. Java Socket网络编程的经典例子(转)

    事实上网络编程简单的理解就是两台计算机相互通讯数据而已,对于程序员而言,去掌握一种编程接口并使用一种编程模型相对就会显得简单的多了,Java SDK提供一些相对简单的Api来完成这些工作.Socket ...

  3. java之NIO编程

    所谓行文如编程,随笔好比java文件,文章好比类,参考文献是import,那么目录就是方法定义. 本篇文章处在分析thrift的nonblocking server之前,因为后者要依赖该篇文章的知识. ...

  4. Java Socket NIO入门

    Java Socket.SocketServer的读写.连接事件监听,都是阻塞式的.Java提供了另外一种非阻塞式读写.连接事件监听方式——NIO.本文简单的介绍一个NIO Socket入门例子,原理 ...

  5. Java Socket网络编程Server端详解

    Socket通信:分为客户端和服务端的socket代码. Java SDK提供一些相对简单的Api来完成.对于Java而言.这些Api存在与java.net 这个包里面.因此只要导入这个包就可以开始网 ...

  6. 【Socket】Java Socket基础编程

    Socket是Java网络编程的基础,了解还是有好处的, 这篇文章主要讲解Socket的基础编程.Socket用在哪呢,主要用在进程间,网络间通信.本篇比较长,特别做了个目录: 一.Socket通信基 ...

  7. Java Socket网络编程学习笔记(一)

    0.前言 其实大概半年前就已经看过网络编程Socket的知识了(传统IO),但是因为长时间的不使用导致忘的一干二净,最近正好准备校招,又重新看了网络编程这一章, 是传统IO(BIO)相关的内容,故在此 ...

  8. Java Socket NIO详解(转)

    java选择器(Selector)是用来干嘛的? 2009-01-12 22:21jsptdut | 分类:JAVA相关 | 浏览8901次 如题,不要贴api的,上面的写的我看不懂希望大家能给我个通 ...

  9. 循序渐进Java Socket网络编程(多客户端、信息共享、文件传输)

    目录[-] 一.TCP/IP协议 二.TCP与UDP 三.Socket是什么 四.Java中的Socket 五.基本的Client/Server程序 六.多客户端连接服务器 七.信息共享 八.文件传输 ...

随机推荐

  1. JBoss部署项目log4j配置会造成死锁问题,浏览器访问一直pending状态

    今天将项目部署到JBoss服务器上,部署成功后,浏览器访问页面一直在等待响应. 查了很长时间,最后在服务器上通过jstack pid命令查看Java堆栈信息,发现了有两个线程死锁. 看到造成死锁的原因 ...

  2. wap网站获取访问者手机号PHP类文件

    <?php /** * 类名: mobile * 描述: 手机信息类 * 其他: */ class mobile { /** * 函数名称: getPhoneNumber * 函数功能: 取手机 ...

  3. delphi 仅带下划线的TEdit控件

    在做录入框的时候,很希望有一个只带下划线的文本框,网上介绍的很多,有自己做组件的,须不知Delphi下只需要简单设置几个属性即可达到目的.

  4. 1064. Complete Binary Search Tree

    二叉排序树: http://www.patest.cn/contests/pat-a-practise/1064 #include <iostream> #include <vect ...

  5. oracle 导入报错 ORA-00959: tablespace 'HB' does not exist

    导入oracle 时发现有几张表导入时一直报错: 报错信息:IMP-00003: ORACLE error 959 encountered   ORA-00959: tablespace 'HB' d ...

  6. 元类metaClass

    metaClass 实现动态改变对象的能力,这点特别像python(metaClass),Python中类(不是元类)的概念借鉴于Smalltalk groovy demo: class Person ...

  7. Lua基础之语法

    目录:1.输出2.注释3.控制语句4.赋值语句5.运算符6.关键字7.变量类型8.其他 原文地址http://blog.csdn.net/dingkun520wy/article/details/49 ...

  8. 判断webpart类型 How can I tell what type a web part is?

    using(new SPSite("http://mysite/myweb").OpenWeb()){ //give relative path of the webpartpag ...

  9. Qt编译postgreSQL驱动

    安装postgreSQL,安装目录下的lib和bin添加到path 打开Qt安装目录,找到src\plugins\sqldrivers\psql编辑psql.pro,添加INCLUDEPATH += ...

  10. Does not contain a valid host:port authority: Master:8031 (configuration property 'yarn.resourcemanager.resource-tracker.address')

    问题解决: 这个错误是:yarn里面的配置的格式有错误:如: <property> <name>yarn.resourcemanager.address</name> ...