NIO 예제 프로그램
11816 단어 Java
package cn.fzmili.archetype.nio;
import java.io.IOException;
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;
import java.util.Iterator;
import java.util.Scanner;
import java.util.Set;
/**
* 2-4
*
* @author fzmili
* : start()--------- 。 main 。start() 。
* main()---------- 。
*/
public class EchoClient {
private InetSocketAddress address;
private ByteBuffer wBuffer = ByteBuffer.allocate(1024);
private ByteBuffer rBuffer = ByteBuffer.allocate(1024);
private Charset charset = Charset.forName("UTF-8");//
public EchoClient(String host, int port) {
this.address = new InetSocketAddress(host, port);
}
public EchoClient(InetSocketAddress address) {
this.address = address;
}
public void start() throws Exception {// 。
/// //
final SocketChannel channel;
channel = SocketChannel.open();// 。
//channel.configureBlocking(false);// ,
channel.connect(address);// , false,
//
if(channel.isConnectionPending())
channel.finishConnect();// , , , , 。
if(!channel.isConnected()){
System.out.println("connecting fail");
return;
}
//
System.out.println("Connecting Success!");
Scanner scanner = new Scanner(System.in);//scanner 。
String text=scanner.nextLine();// 。
text+='
';// scanner.nextLine() , 。
System.out.println(" :"+text);
scanner.close();
System.in.close();
// 。
wBuffer.put(charset.encode(text));
wBuffer.flip();
channel.write(wBuffer);
int readBytes=channel.read(rBuffer);// ,
System.out.println(" :" + getString(rBuffer));
rBuffer.clear();
channel.close();
}
public static String getString(ByteBuffer buffer) {
String string = "";
try {
for (int i = 0; i < buffer.position(); i++) {
string += (char) buffer.get(i);// , 。
}
return string;
} catch (Exception ex) {
ex.printStackTrace();
return "";
}
}
public static void main(String[] args) throws NumberFormatException {
InetSocketAddress address;
switch (args.length) {
case 0:// IP, ,
address = new InetSocketAddress("127.0.0.1", 9999);
break;
case 2:// , ,
{
String ip = args[0];
int port = Integer.parseInt(args[1]);
address = new InetSocketAddress(ip, port);
}
default://
System.err.println("Usage: " + EchoClient.class.getSimpleName() + " ");
return;
}
try {
new EchoClient(address).start();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("--- ----");
}
}
2. 서버 프로그램
package cn.fzmili.archetype.nio;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.NotYetConnectedException;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
public class EchoServer {
private InetSocketAddress address;
private final int bufferSize = 2048;
public EchoServer(String host, int port) {
this.address = new InetSocketAddress(host, port);
}
public EchoServer(InetSocketAddress address) {
this.address = address;
}
public void start() {
///init()
Selector selector = null;
try {
// Channel Selector
ServerSocketChannel channel = ServerSocketChannel.open();
selector = Selector.open();
channel.configureBlocking(false);//
channel.bind(this.address);
/*
* Channel selector,
* 4 :electionKey.OP_CONNECT SelectionKey.OP_ACCEPT SelectionKey.OP_READ SelectionKey.OP_WRITE
*OP_CONNECT---- ,
*OP_ACCEPT-----
*OP_READ & OP_WRITE-------- /
*/
channel.register(selector, SelectionKey.OP_ACCEPT);
System.out.println("Server started .... port:" + address.getPort());
} catch (Exception e) {
System.out.println("Error-" + e.getMessage());
return;
}
// ///
Map buffers = new HashMap<>();// Channel ByteBuffer, 。
try {
int id = 0;
while (true) {// 。
Thread.sleep(1 * 1000);
/*
* , 。
* 。 Channel。
* selector channell。 。
*select() ,
*/
selector.select();
/// init() /
Set readySelectionKey = selector.selectedKeys();
Iterator it = readySelectionKey.iterator();
//
while (it.hasNext()) {
SelectionKey channelKey = it.next();
//Accept--------- TCP
if (channelKey.isAcceptable()) {
/*
* ,
* ( ), ,
* Channel Selector.channel() 。SelectionKey 。
*/
ServerSocketChannel channel = (ServerSocketChannel) channelKey.channel();
channel.accept()
.configureBlocking(false)
.register(selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE)// selector channel, Chanenl SelectionKey, Key Channel , Channel。
.attach(++id);// SelectionKey , Key Channel, Channel 。
/*
:
channel.accept();
channel.configureBlocking(false);
SelectionKey key=channel.register(selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE);// selector channel, Chanenl SelectionKey, Key Channel , Channel。
key.attach(++id);// SelectionKey , Key Channel, Channel 。
*/
buffers.put(id, ByteBuffer.allocate(bufferSize));// , Channel 。
System.out.println("ChannelID:" + id+"\tConnected");
}
if (channelKey.isReadable()) {// , Channel , Channel。
SocketChannel clientChannel = (SocketChannel) channelKey.channel();
ByteBuffer buf = buffers.get((Integer) channelKey.attachment());
try {
int readBytes = clientChannel.read(buf);
if(readBytes==-1) continue;// read=-1 , 。
System.out.print("ChannelID:" + channelKey.attachment()+ "\tInput");
System.out.print("\tReadBytes:" + readBytes);
System.out.println("\tContent:" + getString(buf));//getString , 。
} catch (Exception e) {
clientChannel.close();
channelKey.cancel();
System.out.println("channelID:"+channelKey.attachment()+"\tClosed");
continue;
}
}
if (channelKey.isWritable()) {//
// System.out.println(channelKey.attachment()+ " - ");
SocketChannel clientChannel = (SocketChannel) channelKey.channel();
ByteBuffer buf = buffers.get((Integer) channelKey.attachment());
/*
*buf.position----------
*buf.get(index)------------ 。
*/
if (buf.position() > 0) {// ByteBuffer , 。
if (buf.get(buf.position() - 1) == '
') {
buf.flip();
clientChannel.write(buf);
buf.clear();
}
}
}
// removed , ,
// removed , .next() remove
it.remove();
}
}
} catch (Exception e) {
// TODO: handle exception
System.out.println("Error - " + e.getMessage());
e.printStackTrace();
} finally {
if (selector != null) {
try {
selector.close();
} catch (IOException e) {
System.out.println("Error-" + e.getMessage());
e.printStackTrace();
}
}
}
}
// , 。
public static String getString(ByteBuffer buffer) {
String string = "";
try {
for (int i = 0; i < buffer.position(); i++) {
string += (char) buffer.get(i);// , 。
}
return string;
} catch (Exception ex) {
ex.printStackTrace();
return "";
}
}
public static void main(String[] args) throws Exception {
InetSocketAddress address;
switch (args.length) {
case 0:// IP, ,
address = new InetSocketAddress("127.0.0.1", 9999);
break;
case 1:// (IP )
{
// ( , NumberFormatException)
int port = Integer.parseInt(args[0]);
address = new InetSocketAddress(9999);
break;
}
case 2:// , ,
{
String ip = args[0];
int port = Integer.parseInt(args[0]);
address = new InetSocketAddress(ip, port);
}
default://
System.err.println("Usage: " + EchoServer.class.getSimpleName() + " ");
return;
}
new EchoServer(address).start();
}
}
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
JPA + QueryDSL 계층형 댓글, 대댓글 구현(2)이번엔 전편에 이어서 계층형 댓글, 대댓글을 다시 리팩토링해볼 예정이다. 이전 게시글에서는 계층형 댓글, 대댓글을 구현은 되었지만 N+1 문제가 있었다. 이번에는 그 N+1 문제를 해결해 볼 것이다. 위의 로직은 이...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.