服务器端:

import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
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;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CharsetEncoder;
import java.util.Iterator;

public class TCPServer {

	protected Selector selector;
	protected Charset charset = Charset.forName("UTF-8");
	protected CharsetEncoder charsetEncoder = charset.newEncoder();
	protected CharsetDecoder charsetDecoder = charset.newDecoder();
	int count = 1;

	/**
	 * @throws Exception
	 */
	public TCPServer() throws Exception{
		this(8888);
	}

	/**
	 * @param port
	 * @throws Exception
	 */
	public TCPServer(int port) throws Exception {
		selector = Selector.open();
		ServerSocketChannel ssc = ServerSocketChannel.open();
		ssc.socket().bind(new InetSocketAddress(port)); // port
		ssc.configureBlocking(false);
		ssc.register(selector, SelectionKey.OP_ACCEPT);// register

		while (true) {
			// selector 线程。select() 会阻塞,直到有客户端连接,或者有消息读入
			selector.select();
			Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
			while (iterator.hasNext()) {
				SelectionKey selectionKey = iterator.next();
				iterator.remove(); // 删除此消息
				// 并在当前线程内处理
				handleSelectionKey(selectionKey);
			}
		}

	}

	/**
	 * @param selectionKey
	 * @throws Exception
	 */
	public void handleSelectionKey(SelectionKey selectionKey) throws Exception {
		if (selectionKey.isAcceptable()) {
			ServerSocketChannel ssc = (ServerSocketChannel) selectionKey.channel();
			SocketChannel socketChannel = ssc.accept();
			socketChannel.configureBlocking(false);
			Socket socket = socketChannel.socket();
			// 立即注册一个 OP_READ 的SelectionKey, 接收客户端的消息
			SelectionKey key = socketChannel.register(selector,SelectionKey.OP_READ);

			SocketAddress clientInfo = socket.getRemoteSocketAddress();
			key.attach("第 " + (count++) + " 个客户端 [" + clientInfo + "]");
			// 打印
			println(key.attachment() + " 连接成功");

		} else if (selectionKey.isReadable()) {

			// 有消息进来
			ByteBuffer byteBuffer = ByteBuffer.allocate(100);
			SocketChannel sc = (SocketChannel) selectionKey.channel();

			try {
				int len = sc.read(byteBuffer);
				// 如果len>0,表示有输入。如果len==0, 表示输入结束。需要关闭 socketChannel
				if (len > 0) {
					byteBuffer.flip();
					String msg = charsetDecoder.decode(byteBuffer).toString();
					println(selectionKey.attachment() + " :" + msg);

					// 根据客户端的消息,查找到对应的输出
					String newMsg = "****************";
					ByteBuffer bt = charsetEncoder.encode(CharBuffer.wrap(newMsg + "\n"));
					sc.write(bt);
				} else {
					// 输入结束,关闭 socketChannel
					println(selectionKey.attachment()+ " 已关闭连接");
					sc.close();
				}

			} catch (Exception e) {
				// 如果read抛出异常,表示连接异常中断,需要关闭 socketChannel
				e.printStackTrace();
				sc.close();
			}
		} else if (selectionKey.isWritable()) {
			println("TODO: isWritable()");
		} else if (selectionKey.isConnectable()) {
			println("TODO: isConnectable()");
		} else {
			println("TODO: else");
		}

	}

	/**
	 * @param object
	 */
	public static void println(Object object) {
		System.out.println(object);
	}

	/**
	 * @param args
	 * @throws Exception
	 */
	public static void main(String[] args) throws Exception {
		new TCPServer();
	}

}

客户端:

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;
import java.io.InputStream;

public class TCPClient extends Thread {

	public void run() {
		try {
			Socket socket = new Socket("127.0.0.1", 8888);
			OutputStream ous = socket.getOutputStream();
			InputStream ins = socket.getInputStream();
			BufferedReader r = new BufferedReader(new InputStreamReader(ins, "UTF-8"));

			// 发送服务器
			ous.write(">>>>>>>>>>>>>>>>".getBytes("UTF-8"));
			ous.flush();
			// 接收给服务器
			System.out.println(">>>> " + r.readLine());

			// 发送服务器
			ous.write("<<<<<<<<<<<<<<<<".getBytes("UTF-8"));
			ous.flush();
			// 接收服务器
			System.out.println(">>>> " + r.readLine());

			Thread.sleep(3*1000);

			ins.close();
			ous.close();
			socket.close();

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	/**
	 * @param args
	 * @throws Exception
	 */
	public static void main(String[] args) throws Exception {
		for (int i = 0; i < 3; i++) {
			try {
				new TCPClient().start();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

	}

}

Java异步通信的更多相关文章

  1. Spark案例分析

    一.需求:计算网页访问量前三名 import org.apache.spark.rdd.RDD import org.apache.spark.{SparkConf, SparkContext} /* ...

  2. JAVA NIO 类库的异步通信框架netty和mina

    Netty 和 Mina 我究竟该选择哪个? 根据我的经验,无论选择哪个,都是个正确的选择.两者各有千秋,Netty 在内存管理方面更胜一筹,综合性能也更优.但是,API 变更的管理和兼容性做的不是太 ...

  3. JAVA NIO异步通信框架MINA选型和使用的几个细节(概述入门,UDP, 心跳)

    Apache MINA 2 是一个开发高性能和高可伸缩性网络应用程序的网络应用框架.它提供了一个抽象的事件驱动的异步 API,可以使用 TCP/IP.UDP/IP.串口和虚拟机内部的管道等传输方式.A ...

  4. c#与JAVA利用SOCKET实现异步通信的SanNiuSignal.DLL已开源

    大家好,前段时间C#的SanNiuSignal.DLL已开源;因部分用户特需要JAVA版的SanNiuSignal;现在只能把半成品先拿出来暂时给他们用了,以后再慢慢改进; JAVA版目前已实现跟C# ...

  5. Java基础知识强化之网络编程笔记24:Android网络通信之 AndroidAsync(基于nio的异步通信库)

    1. AndroidAsync   AndroidAsync 是一个基于nio的异步socket ,http(客户端服务器端),websocket,socket.io库,AndroidAsync 是一 ...

  6. Java消息队列--JMS概述

    1.什么是JMS JMS即Java消息服务(Java Message Service)应用程序接口,是一个Java平台中关于面向消息中间件(MOM)的API,用于在两个应用程序之间,或分布式系统中发送 ...

  7. 【历史】JavaScript和Java没啥关系!————JavaScript简史

    文章的开始先上张图: 图片拍摄自北京图书大厦,代表着现在国内应该是绝大部分书店的现状--Javascript书籍放在Java类当中.甚至很多业内人也一直认为Javascript是Java语言在浏览器内 ...

  8. 3.开发Java消息驱动bean实例代码

    java消息服务(JMS)是用于访问企业消息系统的开发商中立的API.企业消息系统可以协助应用软件通过网络进行消息交互.应用程序A发送一条消息到消息服务器的某个目的地(Destination),然后消 ...

  9. JMS(Java消息服务)入门教程

    什么是Java消息服务 Java消息服务指的是两个应用程序之间进行异步通信的API,它为标准消息协议和消息服务提供了一组通用接口,包括创建.发送.读取消息等,用于支持JAVA应用程序开发.在J2EE中 ...

随机推荐

  1. python正则表达式与Re库

    正则表达式是用来简洁表达一组字符串的表达式,一行胜千言,有点类似于数列的通项公式. 在python中提供了re库(regular expression)即正则表达式库,内置于python的标准库中,导 ...

  2. quartz入门详解

    http://www.cnblogs.com/monian/p/3822980.html http://www.blogjava.NET/baoyaer/articles/155645.html 另: ...

  3. div,margin,padding

    <!-- 类比礼品盒里装方块月饼.月饼的食用部分(我们把它称之为月饼肉身)要装在小包装盒里,月饼肉身即为content.月饼肉身与直接包裹它的小包装盒(我们把它叫做月饼的衣服)之间的距离叫pad ...

  4. gulp将多张小图自动合成雪碧图

    最近一直在做移动端的改版项目,做之前老大就跟我说了好几次,说这次改版一定要用雪碧图减少一个页面的图片的请求次数,能加快页面的加载速度就一定要加快,我说可以.因为之前的项目开发时间过短,也没有时间去慢慢 ...

  5. Python小代码_5_二维矩阵转置

    使用列表推导式实现二维矩阵转置 matrix = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]] print(matrix) matrix_t = [[ro ...

  6. Socket网络编程详解

    一,socket的起源 socket一词的起源 在组网领域的首次使用是在1970年2月12日发布的文献IETF RFC33中发现的, 撰写者为Stephen Carr.Steve Crocker和Vi ...

  7. UI相关

    前端 UI 框架 https://github.com/twbs/bootstrap https://github.com/google/material-design-lite https://gi ...

  8. 网络编程练习这些就ok

    1,什么是C/S架构? C指的是client(客户端软件),S指的是Server(服务端软件) 一个C/S架构就是,实现服务端软件与客户端软件基于网络通信. 互联网中处处是C/S架构     如123 ...

  9. Codeforces Round #305 (Div. 2) A. Mike and Fax 暴力回文串

     A. Mike and Fax Time Limit: 20 Sec  Memory Limit: 256 MB 题目连接 http://codeforces.com/contest/548/pro ...

  10. 20160219.CCPP体系详解(0029天)

    程序片段(01):ReplaceAll.c 内容概要:ReplaceAll #define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #incl ...