在非阻塞模式下,EchoServer只需要启动一个主线程,就能同时处理3件事:
1,接收客户的连接
2,接收客户发送的数据
3,接收客户发回响应的数据
package com.test.socket.nio.nonblocking;
import java.io.IOException;
import java.net.InetSocketAddress;
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.util.Iterator;
import java.util.Set;
/**
* 使用非阻塞模式的SocketChannel,ServerSocketChannel.
*/
public class EchoServer {
private Selector selector = null;
private ServerSocketChannel serverSocketChannel = null;
private int port = 8000;
private Charset charset = Charset.forName("GBK");
public EchoServer() throws IOException {
//创建一个selector对象
selector = Selector.open();
serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.socket().setReuseAddress(true);
//使serverSocketChannel工作于非阻塞模式
serverSocketChannel.configureBlocking(false);
serverSocketChannel.socket().bind(new InetSocketAddress(port));
System.out.println("服务器启动...");
}
public void service() throws IOException{
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
while(selector.select()>0){
Set readyKeys = selector.selectedKeys();
Iterator it = readyKeys.iterator();
while(it.hasNext()){
SelectionKey key = null;
try{
key = (SelectionKey)it.next();
it.remove();
if(key.isAcceptable()){
ServerSocketChannel ssc = (ServerSocketChannel)key.channel();
SocketChannel socketChannel = (SocketChannel)ssc.accept();
System.out.println("接收到客户连接,来自:"+ socketChannel.socket().getInetAddress() + ":"
+ socketChannel.socket().getPort());
socketChannel.configureBlocking(false);
ByteBuffer buffer = ByteBuffer.allocate(1024);
socketChannel.register(selector, SelectionKey.OP_READ|SelectionKey.OP_WRITE, buffer);
}
if(key.isReadable()){
receive(key);
}
if(key.isWritable()){
send(key);
}
}catch (IOException e) {
e.printStackTrace();
try{
if(key!=null){
key.cancel();
key.channel().close();
}
}catch (Exception ex) {
ex.printStackTrace();
}
}
}
}
}
public void send(SelectionKey key)throws IOException{
ByteBuffer buffer = (ByteBuffer)key.attachment();
SocketChannel socketChannel = (SocketChannel) key.channel();
buffer.flip();//把极限设为位置,把位置设为0
String data = decode(buffer);
if(data.indexOf("\r\n") == -1){
return;
}
String outputData = data.substring(0,data.indexOf("\n")+1);
System.out.print(outputData);
ByteBuffer outputBuffer = encode("echo:"+outputData);
while(outputBuffer.hasRemaining()){
socketChannel.write(outputBuffer);
}
ByteBuffer temp = encode(outputData);
buffer.position(temp.limit());
buffer.compact();//删除已经处理的字符串
if(outputData.equals("bye\r\n")){
key.cancel();
socketChannel.close();
System.out.println("关闭与客户端的连接");
}
}
public void receive(SelectionKey key)throws IOException{
ByteBuffer buffer = (ByteBuffer) key.attachment();
SocketChannel socketChannel = (SocketChannel) key.channel();
ByteBuffer readBuff = ByteBuffer.allocate(32);
socketChannel.read(readBuff);
readBuff.flip();
buffer.limit(buffer.capacity());
buffer.put(readBuff);
}
public String decode(ByteBuffer buffer){
CharBuffer charBuffer = charset.decode(buffer);
return charBuffer.toString();
}
public ByteBuffer encode(String str){
return charset.encode(str);
}
public static void main(String[] args) throws IOException {
new EchoServer().service();
}
}
非阻塞的EchoClient:利用非阻塞模式来实现异步通信
package com.test.socket.nio.nonblocking;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.util.Iterator;
import java.util.Set;
public class EchoClient {
private SocketChannel socketChannel = null;
private ByteBuffer sendBuffer = ByteBuffer.allocate(1024);
private ByteBuffer receiveBuffer = ByteBuffer.allocate(1024);
private Charset charset = Charset.forName("GBK");
private Selector selector;
public EchoClient() throws IOException {
socketChannel = SocketChannel.open();
InetAddress ia = InetAddress.getLocalHost();
InetSocketAddress isa = new InetSocketAddress(ia,8000);
socketChannel.connect(isa);
socketChannel.configureBlocking(false);
System.out.println("与服务器的连接建立成功");
selector = Selector.open();
}
public static void main(String[] args) throws IOException {
final EchoClient client = new EchoClient();
Thread receiver = new Thread(){
public void run(){
client.receiveFromUser();
}
};
receiver.start();
client.talk();
}
public void receiveFromUser(){
try{
BufferedReader localReader = new BufferedReader(new InputStreamReader(System.in));
String msg = null;
while((msg = localReader.readLine())!=null){
synchronized (sendBuffer) {
sendBuffer.put(encode(msg+"\r\n"));
}
if(msg.equals("bye"))
break;
}
}catch (IOException e) {
e.printStackTrace();
}
}
public void talk()throws IOException{
try{
socketChannel.register(selector, SelectionKey.OP_READ|SelectionKey.OP_WRITE);
while(selector.select()>0){
Set readyKeys = selector.selectedKeys();
Iterator it = readyKeys.iterator();
while(it.hasNext()){
SelectionKey key = null;
try{
key = (SelectionKey)it.next();
it.remove();
if(key.isReadable()){
receive(key);
}
if(key.isWritable()){
send(key);
}
}catch (IOException e) {
e.printStackTrace();
try{
if(key!=null){
key.cancel();
key.channel().close();
}
}catch (Exception ex) {
ex.printStackTrace();
}
}
}
}
}catch (IOException e) {
e.printStackTrace();
}finally{
try{
socketChannel.close();
}catch (IOException e) {
e.printStackTrace();
}
}
}
public void send(SelectionKey key)throws IOException{
SocketChannel socketChannel = (SocketChannel) key.channel();
synchronized (sendBuffer) {
sendBuffer.flip();
socketChannel.write(sendBuffer);
sendBuffer.compact();
}
}
public void receive(SelectionKey key)throws IOException{
//接收EchoServer发送的数据,把它放到receiveBuffer中
//如果receiverBuffer中有一行数据,就打印这行数据,然后把它从receiverBuffer中删除
SocketChannel socketChannel = (SocketChannel) key.channel();
socketChannel.read(receiveBuffer);
receiveBuffer.flip();
String receiveData = decode(receiveBuffer);
if(receiveData.indexOf("\n") == -1){
return;
}
String outputData = receiveData.substring(0,receiveData.indexOf("\n")+1);
System.out.println(outputData);
if(outputData.equals("echo:bye\r\n")){
key.cancel();
socketChannel.close();
System.out.println("关闭与服务器的连接");
selector.close();
System.exit(0);
}
ByteBuffer temp = encode(outputData);
receiveBuffer.position(temp.limit());
receiveBuffer.compact();
}
public String decode(ByteBuffer buffer){
CharBuffer charBuffer = charset.decode(buffer);
return charBuffer.toString();
}
public ByteBuffer encode(String str){
return charset.encode(str);
}
}
分享到:
相关推荐
本篇文章将深入探讨如何使用Java NIO(非阻塞I/O)来实现阻塞多线程通信,这对于高性能服务器端应用尤其重要。我们将会分析`EchoServer.java`、`EchoClient.java`和`SocketUtils.java`这三个文件中的关键知识点。 ...
本示例通过两个类——EchoServer和EchoClient,展示了如何使用NIO实现基于TCP/IP协议的网络通信。 首先,我们来看`EchoServer`。这个类通常扮演服务端的角色,监听指定端口并接收客户端连接。在Java NIO中,服务器...
5. **性能优化**:DotNetty通过使用异步非阻塞I/O模型(NIO),实现了高度并发和低延迟。此外,它的内存管理机制(如ByteBuf)减少了不必要的对象创建和复制,提高了效率。开发者可以通过理解这些机制,进一步优化...
- 使用Java NIO的`ServerSocketChannel`和`SocketChannel`来处理服务器和客户端的连接,`Selector`和`SelectionKey`用于实现非阻塞特性,确保高效率的并发处理。 - `Buffer`类作为数据的临时存储,`FileChannel`则...
为了提高性能和可靠性,还可以考虑使用NIO(非阻塞I/O)和多线程技术,或者更高级的框架如Netty。 总的来说,Java提供的网络编程API使得开发者能够轻松实现跨进程、跨网络的通信。通过学习和理解EchoServer和...
在实际应用中,你可以进一步扩展它,例如添加错误处理、多线程支持,或者使用NIO(非阻塞I/O)以提高性能。此外,由于UDP的特性,你可能还需要考虑数据包丢失和乱序的问题,尤其是在构建可靠通信系统时。
Java Netty 是一个高性能、异步事件驱动的网络应用程序...通过阅读和理解"JavaNetty.rar"中的代码,特别是EchoClient和EchoServer的实现,你可以深入学习Netty的工作原理,以及如何利用它来构建高效的消息通信系统。
Netty还提供了很多开箱即用的组件,如EchoServer和EchoClient。EchoServer是一个回显服务器,它将收到的每个消息直接返回给发送方,用于测试网络连接和消息的完整性。EchoClient则是一个回显客户端,它向服务器发送...
在Java中,这类应用通常使用IO流或NIO(非阻塞I/O)进行数据传输,可能还会涉及线程管理和数据库操作。 3. **tcp.java**:此文件可能包含了一个简单的TCP网络通信示例。TCP(传输控制协议)是互联网上最常用的一种...
为了提高效率,可以采用多线程或者非阻塞I/O(如NIO,Java的新I/O库)来改进。但是,对于初学者来说,理解单线程阻塞模型是学习网络编程的基础,有助于深入理解Socket通信的工作原理。 此外,源码分析可以帮助我们...
Netty 是由 JBoss 组织开源的一个网络通信框架,基于 Java NIO(非阻塞I/O)构建,提供了一套高度抽象和优化的 API,使得开发者可以轻松地处理网络连接的各种复杂情况。Netty 提供了多种传输类型,如 TCP、UDP 以及...
可能涉及的文件包括配置文件(如`applicationContext.xml`),MINA的服务类(如`EchoServer`),客户端类(如`EchoClient`),以及相关的过滤器和协议处理器。 6. **配置示例**:在`applicationContext.xml`中,...