客户端代码:

/**
*
*/
package com.bobohe.nio; import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset; /**
* 实现TCP/IP+NIO 方式的系统间通讯的代码,客户端:
*
* @author solo
*/
public class NioClient { /**
* create solo
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
String host = "127.0.0.1";
int port = 9527; Selector selector = Selector.open(); SocketChannel clientChannel = SocketChannel.open();
clientChannel.configureBlocking(false);
clientChannel.connect(new InetSocketAddress(host, port)); clientChannel.register(selector, SelectionKey.OP_CONNECT); BufferedReader systemIn = new BufferedReader(new InputStreamReader(System.in));
while (true) {
if (clientChannel.isConnected()) {
String command = systemIn.readLine();
clientChannel.write(Charset.forName("UTF-8").encode(command)); if (command == null || "quit".equalsIgnoreCase(command)) {
System.out.println("Client quit!"); systemIn.close();
clientChannel.close();
selector.close();
System.exit(0);
} } //最长阻塞10s
int nKeys = selector.select(10 * 1000);
if (nKeys > 0) {
for (SelectionKey selectionKey : selector.selectedKeys()) {
if (selectionKey.isConnectable()) {
SocketChannel socketChannel = (SocketChannel)selectionKey.channel();
socketChannel.configureBlocking(false);
socketChannel.register(selector, SelectionKey.OP_READ);
socketChannel.finishConnect();
} else if (selectionKey.isReadable()) {
SocketChannel socketChannel = (SocketChannel)selectionKey.channel();
StringBuilder sb = new StringBuilder(); ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
try {
int readBytes = 0;
int ret = 0;
while ((ret = socketChannel.read(byteBuffer)) > 0) {
readBytes += ret;
byteBuffer.flip(); sb.append(Charset.forName("UTF-8").decode(byteBuffer).toString()); byteBuffer.clear();
} if (readBytes == 0) {
/*
* handle Exception
*/
System.err.println("handle opposite close Exception");
socketChannel.close();
}
} catch (IOException e) {
/*
* handle Exception
*/
System.err.println("handle read Exception");
socketChannel.close();
} finally {
byteBuffer.clear();
} String message = sb.toString();
System.out.println(message);
}
}
selector.selectedKeys().clear(); } else {
/*
* handle Exception
* 三秒没有响应则打印错误信息
*/
System.err.println("handle select timeout Exception");
clientChannel.close();
} }
} }

服务端代码:

/**
*
*/ package com.bobohe.nio; import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
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.nio.charset.Charset; /**
* 实现TCP/IP+NIO 方式的系统间通讯的代码,服务器端: SocketChannel和ServerSocketChannel两个关键的类,网络IO
* 的操作则改为通过ByteBuffer来实现。
*
* @author solo
*/
public class NioServer { /**
* create by solo
*
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
int port = 9527;
System.out.println("Server listen on port: " + port); Selector selector = Selector.open(); ServerSocketChannel serverChannel = ServerSocketChannel.open();
ServerSocket serverSocket = serverChannel.socket();
serverSocket.bind(new InetSocketAddress(port));
serverChannel.configureBlocking(false); serverChannel.register(selector, SelectionKey.OP_ACCEPT);
while (true) {
int nKeys = selector.select();
if (nKeys > 0) {
for (SelectionKey selectionKey : selector.selectedKeys()) {
if (selectionKey.isAcceptable()) {
ServerSocketChannel tempServerChannel = (ServerSocketChannel) selectionKey
.channel();
SocketChannel socketChannel = tempServerChannel
.accept();
if (socketChannel == null) {
continue;
} socketChannel.configureBlocking(false);
socketChannel.register(selector, SelectionKey.OP_READ);
} else if (selectionKey.isReadable()) {
// try { Thread.sleep(5000); } catch
// (InterruptedException e) { e.printStackTrace(); }
SocketChannel socketChannel = (SocketChannel) selectionKey
.channel(); StringBuilder sb = new StringBuilder();
ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
try {
int readBytes = 0;
int ret = 0;
while ((ret = socketChannel.read(byteBuffer)) > 0) {
readBytes += ret;
byteBuffer.flip(); sb.append(Charset.forName("UTF-8")
.decode(byteBuffer).toString()); byteBuffer.clear();
} if (readBytes == 0) {
/*
* handle Exception
*/
System.err
.println("handle opposite close Exception");
socketChannel.close();
} String message = sb.toString();
System.out.println("client: "
+ message);
if ("quit".equalsIgnoreCase(message.toString()
.trim())) {
System.out.println("Client has been quit!"); socketChannel.close();
} else if ("serverquit".equalsIgnoreCase(message
.trim())) {
System.out.println("Server has been shutdown!"); socketChannel.close();
serverChannel.close();
selector.close();
System.exit(0);
} else {
socketChannel.write(Charset.forName("UTF-8").encode("Server Handler Done!"));
}
} catch (IOException e) {
/*
* handle Exception
*/
System.err.println("handle read Exception");
socketChannel.close();
} finally {
byteBuffer.clear();
} }
}
selector.selectedKeys().clear(); }
}
} }

170407、java基于nio工作方式的socket通信的更多相关文章

  1. JAVA基础知识之网络编程——-基于NIO的非阻塞Socket通信

    阻塞IO与非阻塞IO 通常情况下的Socket都是阻塞式的, 程序的输入输出都会让当前线程进入阻塞状态, 因此服务器需要为每一个客户端都创建一个线程. 从JAVA1.4开始引入了NIO API, NI ...

  2. java体系结构与工作方式 《深入分析java web 技术内幕》第七章

    java体系结构与工作方式 7.1 JVM体系结构 何谓JVM JVM(Java Virtual Machine) 通过模拟一个计算机来达到一个计算机所具有的计算功能 指令集:计算机所能识别的机器语言 ...

  3. 基于Tcp协议的简单Socket通信实例(JAVA)

    好久没写博客了,前段时间忙于做项目,耽误了些时间,今天开始继续写起~ 今天来讲下关于Socket通信的简单应用,关于什么是Socket以及一些网络编程的基础,这里就不提了,只记录最简单易懂实用的东西. ...

  4. 多线程方式实现Socket通信

    一.首先,介绍下两类传输协议:TCP:UDP TCP是Tranfer Control Protocol的 简称,是一种面向连接的保证可靠传输的协议.通过TCP协议传输,得到的是一个顺序的无差错的数据流 ...

  5. 坦克大战--Java类型 ---- (3)实现socket通信

    一.实现思路 使用socket通信的一些方法来实现socket通信,客户端和服务端两边需要约定好通信的接口Port(尽量选高的),客户端需要服务端的IP地址,以实现数据交流. 同时,客户端和服务端需要 ...

  6. java之接口开发-初级篇-socket通信

    socket通信实现util包类实现 public class SocketThread extends Thread { public void run() { while (true) { // ...

  7. java学习小笔记(三.socket通信)【转】

    三,socket通信1.http://blog.csdn.net/kongxx/article/details/7288896这个人写的关于socket通信不错,循序渐进式的讲解,用代码示例说明,运用 ...

  8. 基于TCP和UDP的Socket通信

    TCP的Socket通信 TCP是面向连接的,安全的协议,它是一对一的关系 server client 上面只是单个客户端同服务器通信,可使用多线程编程实现多个客户端的通信 UDP的Socket通信 ...

  9. java nio实现非阻塞Socket通信实例

    服务器 package com.java.xiong.Net17; import java.io.IOException; import java.net.InetSocketAddress; imp ...

随机推荐

  1. [原]C#设置文件夹用户权限

    var security = new DirectorySecurity();   string path=@"C:\temp" //设置权限的应用为文件夹本身.子文件夹及文件,所 ...

  2. shell 基础语法

    shell 基础语法 =============================================== 推荐:http://c.biancheng.net/cpp/shell/ ==== ...

  3. 11个常用的Linux命令

    Linux命令行吸引了大多数Linux爱好者.一个正常的Linux用户一般掌握大约50-60个命令来处理每日的任务.今天为你解释下面几个命令:sudo.python.mtr.Ctrl+x+e.nl.s ...

  4. MySQL Fabric部署

    架构描写叙述: 一台主机上安装4个MySQL 服务,当中一个MySQL服务用于存储MySQL Fabric后台数据:另外3个MySQL服务用于主从架构測试.一个主+两个从. 第一部分:二进制方式安装M ...

  5. JQM事件详解

    在前文<使用 jQuery Mobile 与 HTML5 开发 Web App —— jQuery Mobile 默认配置与事件基础>中,Kayo 对 jQuery Mobile 事件的基 ...

  6. 思科ACL不连续通配符掩码的计算

    access-list 120 permit ip 10.0.0.0 0.0.0.191 any     这条ACL看似简单,却又复杂,因为正常我们见到的通配符掩码都是诸如0.0.0.255(255. ...

  7. 本次安装Lion记录

    黑苹果驱动之家 http://it360.org.cn/ Mac安装在Macintosh上是没什么好讲的,也没什么难度,原生的东西.但每次Mac安装在PC上总能折腾一番,驱动.五国.各种报错..今天记 ...

  8. PLSQL 连接不上64位ORACLE数据库解决办法

    http://it.oyksoft.com/post/6003/ huan jing bian liang TNS_ADMIN  D:\OracleClient D:\OracleClient\TNS ...

  9. Adroid—— DVM

     Android DVM   Android 运行环境主要指的虚拟机技术——Dalvik.Android中的所有Java程序都是运行在Dalvik VM上的.Android上的每个程序都有自己的线程, ...

  10. C#_GDI+编程教程

    第7章  C#图形图像编程基础 本章主要介绍使用C#进行图形图像编程基础,其中包括GDI+绘图基础.C#图像处理基础以及简单的图像处理技术. 7.1  GDI+绘图基础 编写图形程序时需要使用GDI( ...