170407、java基于nio工作方式的socket通信
客户端代码:
/**
*
*/
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通信的更多相关文章
- JAVA基础知识之网络编程——-基于NIO的非阻塞Socket通信
阻塞IO与非阻塞IO 通常情况下的Socket都是阻塞式的, 程序的输入输出都会让当前线程进入阻塞状态, 因此服务器需要为每一个客户端都创建一个线程. 从JAVA1.4开始引入了NIO API, NI ...
- java体系结构与工作方式 《深入分析java web 技术内幕》第七章
java体系结构与工作方式 7.1 JVM体系结构 何谓JVM JVM(Java Virtual Machine) 通过模拟一个计算机来达到一个计算机所具有的计算功能 指令集:计算机所能识别的机器语言 ...
- 基于Tcp协议的简单Socket通信实例(JAVA)
好久没写博客了,前段时间忙于做项目,耽误了些时间,今天开始继续写起~ 今天来讲下关于Socket通信的简单应用,关于什么是Socket以及一些网络编程的基础,这里就不提了,只记录最简单易懂实用的东西. ...
- 多线程方式实现Socket通信
一.首先,介绍下两类传输协议:TCP:UDP TCP是Tranfer Control Protocol的 简称,是一种面向连接的保证可靠传输的协议.通过TCP协议传输,得到的是一个顺序的无差错的数据流 ...
- 坦克大战--Java类型 ---- (3)实现socket通信
一.实现思路 使用socket通信的一些方法来实现socket通信,客户端和服务端两边需要约定好通信的接口Port(尽量选高的),客户端需要服务端的IP地址,以实现数据交流. 同时,客户端和服务端需要 ...
- java之接口开发-初级篇-socket通信
socket通信实现util包类实现 public class SocketThread extends Thread { public void run() { while (true) { // ...
- java学习小笔记(三.socket通信)【转】
三,socket通信1.http://blog.csdn.net/kongxx/article/details/7288896这个人写的关于socket通信不错,循序渐进式的讲解,用代码示例说明,运用 ...
- 基于TCP和UDP的Socket通信
TCP的Socket通信 TCP是面向连接的,安全的协议,它是一对一的关系 server client 上面只是单个客户端同服务器通信,可使用多线程编程实现多个客户端的通信 UDP的Socket通信 ...
- java nio实现非阻塞Socket通信实例
服务器 package com.java.xiong.Net17; import java.io.IOException; import java.net.InetSocketAddress; imp ...
随机推荐
- Refresh Tokens: When to Use Them and How They Interact with JWTs
In this post we will explore the concept of refresh tokens as defined by OAuth2. We will learn why t ...
- Apache多虚拟主机多版本PHP(5.2+5.3+5.4)共存运行配置全过程
因为某种需求,可能是因为早期的项目需要低版本的php,和目前开发所用的版本不太一致,我们需要给不同的虚拟主机配置不同版本的PHP.避免去额外配置多个Apache,等iis和apache共存的麻烦. 下 ...
- python随机数seed用法
import random ... def main(): a = random.Random() a.seed(1) print a.random() 这样就可以通过种子取得固定随机值了 网上很多只 ...
- hadoop修改
https://github.com/medcl/elasticsearch-analysis-ik/releases hadoop-/etc/hadoop/core-site.xml <con ...
- JS中同步与异步的理解
你应该知道,javascript语言是一门“单线程”的语言,不像java语言,类继承Thread再来个thread.start就可以开辟一个线程,所以,javascript就像一条流水线,仅仅是一条流 ...
- Linux(Ubuntu/Debian/CentOS/RedHat)下交叉编译boost库
我用的软件版本如下(其他版本编译方法与此完全相同): Boost Ver: 1.55.0Compiler : GNU gcc 4.6 for ARM 1. 确保ARM编译成功安装,并配置好环境变量.2 ...
- 《Google软件测试之道》- Google软件测试介绍
<Google软件测试之道>- Google软件测试介绍 2015-05-21 目录 1 质量与测试 2 角色 3 组织结构 4 爬.走.跑 5 测试类型 相关链接 与Micro ...
- Qt 中彩色图像转换为灰度图
近期在做几个图像处理相关的项目.里面有一个操作就是须要先将彩色图像转换为灰度图像. QImage 有一个convertToFormat方法.最開始一直用这个函数来实现. 可是今天细致看了看,发现这个函 ...
- ad7888 linux driver
/* ADCCONVERT.c : Generate ADC signals from SPI ports, as the A/D control signals. Author: Aaron Fu ...
- Tomcat热部署及错误排查
Maven的热部署 第一步:配置Tomcat的登陆的用户名与密码 C:\apache-tomcat-7.0.33\conf\ tomcat-users.xml 从第36行开始配置 <r ...