server
package nio;
import java.io.*;
import java.net.*;
import java.nio.*;
import java.nio.channels.*;
import java.util.*;
public class Server implements Runnable {
// The port we will listen on
private int port;
// A pre-allocated buffer for encrypting data
private final ByteBuffer buffer = ByteBuffer.allocate(16384);
public Server(int port) {
this.port = port;
new Thread(this).start();
}
public void run() {
try {
// Instead of creating a ServerSocket,
// create a ServerSocketChannel
ServerSocketChannel ssc = ServerSocketChannel.open();
// Set it to non-blocking, so we can use select
ssc.configureBlocking(false);
// Get the Socket connected to this channel, and bind it
// to the listening port
ServerSocket ss = ssc.socket();
InetSocketAddress isa = new InetSocketAddress(port);
ss.bind(isa);
// Create a new Selector for selecting
Selector selector = Selector.open();
// Register the ServerSocketChannel, so we can
// listen for incoming connections
ssc.register(selector, SelectionKey.OP_ACCEPT);
System.out.println("Listening on port " + port);
while (true) {
// See if we've had any activity -- either
// an incoming connection, or incoming data on an
// existing connection
int num = selector.select();
// If we don't have any activity, loop around and wait
// again
if (num == 0) {
continue;
}
// Get the keys corresponding to the activity
// that has been detected, and process them
// one by one
Set keys = selector.selectedKeys();
Iterator it = keys.iterator();
while (it.hasNext()) {
// Get a key representing one of bits of I/O
// activity
SelectionKey key = (SelectionKey) it.next();
// What kind of activity is it?
if ((key.readyOps() & SelectionKey.OP_ACCEPT) == SelectionKey.OP_ACCEPT) {
System.out.println("acc");
// It's an incoming connection.
// Register this socket with the Selector
// so we can listen for input on it
Socket s = ss.accept();
System.out.println("Got connection from " + s);
// Make sure to make it non-blocking, so we can
// use a selector on it.
SocketChannel sc = s.getChannel();
sc.configureBlocking(false);
// Register it with the selector, for reading
sc.register(selector, SelectionKey.OP_READ);
} else if ((key.readyOps() & SelectionKey.OP_READ) == SelectionKey.OP_READ) {
SocketChannel sc = null;
try {
// It's incoming data on a connection, so
// process it
sc = (SocketChannel) key.channel();
boolean ok = processInput(sc);
// If the connection is dead, then remove it
// from the selector and close it
if (!ok) {
key.cancel();
Socket s = null;
try {
s = sc.socket();
s.close();
} catch (IOException ie) {
System.err.println("Error closing socket "
+ s + ": " + ie);
}
}
} catch (IOException ie) {
// On exception, remove this channel from the
// selector
key.cancel();
try {
sc.close();
} catch (IOException ie2) {
System.out.println(ie2);
}
System.out.println("Closed " + sc);
}
}
}
// We remove the selected keys, because we've dealt
// with them.
keys.clear();
}
} catch (IOException ie) {
System.err.println(ie);
}
}
// Do some cheesy encryption on the incoming data,
// and send it back out
private boolean processInput(SocketChannel sc) throws IOException {
buffer.clear();
sc.read(buffer);
buffer.flip();
// If no data, close the connection
if (buffer.limit() == 0) {
return false;
}
// Simple rot-13 encryption
for (int i = 0; i < buffer.limit(); ++i) {
byte b = buffer.get(i);
if ((b >= 'a' && b <= 'm') || (b >= 'A' && b <= 'M')) {
b += 13;
} else if ((b >= 'n' && b <= 'z') || (b >= 'N' && b <= 'Z')) {
b -= 13;
}
buffer.put(i, b);
}
sc.write(buffer);
System.out.println("Processed " + buffer.limit() + " from " + sc);
return true;
}
static public void main(String args[]) throws Exception {
int port = Integer.parseInt(args[0]);
new Server(port);
}
}
client NIO方式实现
/**
*
*/
package com.topsci.xxxxxx.provider.service;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CharsetEncoder;
import java.util.Random;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
*/
class TestClient {
private static Logger logger = LoggerFactory.getLogger(TestClient.class);//slf4j logging
// The host:port combination to connect to
private InetAddress hostAddress;
private int port;
private SocketChannel client;
protected Charset charset = Charset.forName("UTF-8");
protected CharsetEncoder charsetEncoder = charset.newEncoder();
protected CharsetDecoder charsetDecoder = charset.newDecoder();
public TestClient(InetAddress hostAddress, int port) throws IOException{
this.hostAddress = hostAddress;
this.port = port;
// Create a non-blocking socket channel
client = SocketChannel.open();
// client.configureBlocking(false);
// client.register(this.selector, SelectionKey.OP_CONNECT);
// Kick off connection establishment
client.connect(new InetSocketAddress(this.hostAddress, this.port));
}
private void request(String msg){
ByteBuffer buffer = ByteBuffer.allocate(100);
try {
this.client.write(charsetEncoder.encode(CharBuffer.wrap(msg)));
int len = this.client.read(buffer);
if (len > 0){
buffer.flip();
logger.info(charsetDecoder.decode(buffer).toString());
}
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* @param args
* @throws IOException
* @throws UnknownHostException
*/
public static void main(String[] args) throws UnknownHostException, IOException {
// TODO Auto-generated method stub
TestClient client = new TestClient(InetAddress.getByName("localhost"), 9999);
Random random = new Random();
for (int i = 5; i > 0; i--){
String req = "请求编号 " + random.nextInt();
client.request(req);
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
client 传统方式实现
package nio;
import java.io.*;
import java.net.*;
import java.util.*;
public class Client implements Runnable {
private String host;
private int port;
// Bounds on how much we write per cycle
private static final int minWriteSize = 1024;
private static final int maxWriteSize = 65536;
// Bounds on how long we wait between cycles
private static final int minPause = (int) (0.05 * 1000);
private static final int maxPause = (int) (0.5 * 1000);
// Random number generator
Random rand = new Random();
public Client(String host, int port, int numThreads) {
this.host = host;
this.port = port;
for (int i = 0; i < numThreads; ++i) {
new Thread(this).start();
}
}
public void run() {
byte buffer[] = new byte[maxWriteSize];
try {
Socket s = new Socket(host, port);
InputStream in = s.getInputStream();
OutputStream out = s.getOutputStream();
while (true) {
int numToWrite = minWriteSize
+ (int) (rand.nextDouble() * (maxWriteSize - minWriteSize));
for (int i = 0; i < numToWrite; ++i) {
buffer[i] = (byte) rand.nextInt(256);
}
out.write(buffer, 0, numToWrite);
int sofar = 0;
while (sofar < numToWrite) {
sofar += in.read(buffer, sofar, numToWrite - sofar);
}
System.out.println(Thread.currentThread() + " wrote "
+ numToWrite);
int pause = minPause
+ (int) (rand.nextDouble() * (maxPause - minPause));
try {
Thread.sleep(pause);
} catch (InterruptedException ie) {
}
}
} catch (IOException ie) {
ie.printStackTrace();
}
}
static public void main(String args[]) throws Exception {
String host = args[0];
int port = Integer.parseInt(args[1]);
int numThreads = Integer.parseInt(args[2]);
new Client(host, port, numThreads);
}
}
分享到:
相关推荐
本入门文档及示例代码旨在帮助开发者快速理解并掌握Java NIO的基本概念和用法。 一、NIO基础概念 1. **通道(Channels)**:NIO的核心组件之一,它是连接到数据源(如文件、套接字)的通道,可以读写数据。常见的...
示例代码片段 ```java Selector selector = Selector.open(); ServerSocketChannel server = ServerSocketChannel.open().bind(new InetSocketAddress(8080)); server.configureBlocking(false); server.register...
非阻塞I/O(Non-blocking Input/Output,简称NIO)是Java提供的另一种I/O模型,与传统的阻塞I/O模型不同,它允许多个操作并行进行,从而...对于Java初学者来说,这是一个极好的实践资源,可以帮助你快速掌握NIO编程。
通过以上代码,我们构建了一个基于Java NIO的Socket通信示例。客户端发送"Hello, Server!",服务器接收到消息后将其打印出来。这个基础架构可以扩展到更复杂的网络应用,例如聊天服务器、文件传输等。NIO的优势在于...
《NIO与Netty编程-实战讲义详细pdf》可能涵盖了以上所有概念的详细解释,包括代码示例、最佳实践以及常见问题的解决方案。这份讲义将深入讲解如何使用NIO和Netty实现高效网络编程,帮助开发者提升技能,解决实际项目...
在“AsynIOModule”这个压缩包中,可能包含了关于Java NIO和AIO编程的相关示例代码和文档,这些资源可以帮助开发者深入理解和实践这两种异步I/O机制,提升他们在Java网络编程中的技能。通过研究这些代码和文档,...
这个压缩包文件“java-se-master”显然包含了与Java SE相关的各种示例代码,帮助学习者深入理解Java编程语言,特别是其新特性、集合分析、非阻塞I/O(NIO)以及并发编程等关键概念。以下是对这些知识点的详细阐述: ...
这个压缩包文件包含了该书中的示例代码,对于学习和掌握Java核心概念至关重要。以下是根据这些信息解析出的一些关键知识点: 1. **异常处理**:Java的异常处理机制是其强项之一,通过try-catch-finally语句块,...
本文将深入探讨NIO原生API的示例,基于提供的"ServerImpCopy.java"文件名,我们可以推测这是一个关于服务器端NIO实现的示例代码。 在Java NIO中,核心组件包括通道(Channels)、缓冲区(Buffers)和选择器...
### Java网络编程NIO视频教程知识点汇总 #### 1. Java NIO-课程简介 - **主要内容**:简述...通过以上内容的学习,开发者可以全面掌握Java NIO编程的相关技术和最佳实践,为开发高性能网络应用程序打下坚实的基础。
在Java编程领域,NIO(New IO)是一个重要的特性,它是Java 1.4引入的,为处理大量并发连接提供了一种高效的方式。NIO聊天室的实现是学习和理解NIO机制的一个实用示例。在这个项目中,我们将探讨如何使用NIO构建一个...
本教程旨在帮助NIO初学者理解这两种模型的核心概念及其实际应用,通过具体的代码示例来深入探讨其区别。 IO模型,即同步阻塞I/O,主要基于流(Stream)进行操作,分为字节流和字符流两大类。在Java中,IO模型通常...
本篇文章将深入探讨这两个概念,并通过示例代码`NonBlockingServer.java`和`Client.java`来展示其工作原理。 首先,Socket是基于TCP/IP协议的应用层接口,它为应用程序提供了一种在网络中发送和接收数据的方式。...
在"sumsever+client"这个压缩包中,你应该能找到对应的服务器端和客户端源代码文件,通过阅读和运行这些代码,你可以更深入地理解NIO在实际网络编程中的应用。 总结来说,"NIO socket编程小例子 加法服务器"是一个...
【聊天室示例代码】是一种实现在线聊天功能的编程示例,它允许多个用户同时连接到同一平台,进行实时的交流和互动。这种技术在现代互联网应用中非常常见,尤其在社交、协作和客户服务等领域。下面我们将深入探讨聊天...
标题"nio演示代码"表明我们将探讨NIO的实际应用,通过代码示例来理解其工作原理和优势。在CSDN博客中,作者wgyscsf分享了一篇文章,详细介绍了NIO的用法。 在NIO模型中,以下几个核心组件是关键: 1. **通道...
标题“nio.rar_NIO_NIO-socket_java nio_java 实例_java.nio”表明这个压缩包包含了一个关于Java NIO的实例,特别是关于NIO套接字(Socket)的编程示例。NIO套接字是Java NIO库中用于网络通信的关键组件,它们允许...
`TestConnector.java`和`SocketTest.java`可能包含了此类客户端的示例代码,展示如何创建和管理Socket连接,以及发送和接收数据的基本流程。 相比之下,Mina NIO是一种基于Java NIO API的网络通信框架,它利用了多...
通过深入学习以上知识点,并结合"网络编程示例"中的实际代码,开发者可以掌握Java网络编程的基本技能,实现各种网络应用,如聊天室、文件传输、Web服务客户端等。记得在实践中不断探索和优化,提升网络编程能力。