NIO 포트 전송 실현
package example;
/**
*
*/
//import java.io.FileInputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
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.util.HashMap;
import java.util.Iterator;
public class myServer {
public static final int PORTClient = 8085;
public static final int PORTDevice = 8081;
protected static HashMap<String,SelectionKey> map = new HashMap<String, SelectionKey>();
//
protected Selector selector;
protected Selector selector_device;
int clientCount;
int deviceCount;
public myServer() throws Exception {
// socket selector
selector = Selector.open();
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.socket().bind(new InetSocketAddress(PORTClient)); // port
serverSocketChannel.configureBlocking(false);
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);// register
p("Server localhost:" + PORTClient + " started. waiting for clients. ");
//
selector_device=Selector.open();
ServerSocketChannel serverSocketChannelDevice = ServerSocketChannel.open();
serverSocketChannelDevice.socket().bind(new InetSocketAddress(PORTDevice));
serverSocketChannelDevice.configureBlocking(false);
serverSocketChannelDevice.register(selector_device, SelectionKey.OP_ACCEPT);
p("Server localhost:" + PORTDevice + " started. waiting for Device. ");
Client client=new Client();
Device device=new Device();
device.run();
while (true) {
client.run();
}
}
class Client implements Runnable{
@Override
public void run() {
// TODO Auto-generated method stub
try {
// selector 。select() , ,
selector.select();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
while (iterator.hasNext()) {
SelectionKey selectionKey = iterator.next();
// hashmap.put(, selectionKey);
iterator.remove(); //
// 。( , , )
try {
handleSelectionKey(selectionKey);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void start() {
// TODO Auto-generated method stub
}
}
class Device implements Runnable
{
@Override
public void run() {
// TODO Auto-generated method stub
//
try {
selector_device.select();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Iterator<SelectionKey> iteratorDevice = selector_device.selectedKeys().iterator();
while (iteratorDevice.hasNext()) {
SelectionKey selectionKeyDevice = iteratorDevice.next();
System.out.println(selectionKeyDevice);
// hashmap.put(, selectionKey);
iteratorDevice.remove(); //
// 。( , , )
try {
handleDevice(selectionKeyDevice);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void start() {
// TODO Auto-generated method stub
}
}
//
private void handleDevice(SelectionKey selectionKeyDevice) throws IOException {
// TODO Auto-generated method stub
if (selectionKeyDevice.isAcceptable()) {
//
deviceCount++;
System.out.println(deviceCount);
ServerSocketChannel serverSocketChannel = (ServerSocketChannel) selectionKeyDevice.channel();
SocketChannel socketChannel = serverSocketChannel.accept();
socketChannel.configureBlocking(false);
Socket socket = socketChannel.socket();
// OP_READ SelectionKey,
SelectionKey key = socketChannel.register(selector_device, SelectionKey.OP_READ);
System.out.println(key);
String str=socket.getRemoteSocketAddress().toString();
String [] strs = str.split("[:]");
// map
map.put(strs[0], key);
System.out.println(map.get(socket.getRemoteSocketAddress()));
System.out.println(socket.getInetAddress().getHostAddress());
key.attach(" " + deviceCount + " [" + socket.getRemoteSocketAddress() + "]: ");
p(key.attachment() + "\t[connected] =========================================");
} else if (selectionKeyDevice.isReadable()) {
//
ByteBuffer byteBufferD = ByteBuffer.allocate(100);
SocketChannel socketChannel = (SocketChannel) selectionKeyDevice.channel();
try {
int len = socketChannel.read(byteBufferD);
if (len > 0) {
byteBufferD.flip();//flip() , limit position , position 0
socketChannel.write(byteBufferD);
//socketChannelDevice.write(byteBuffer);
} else {
// , socketChannel
p(selectionKeyDevice.attachment() + "read finished. close socketChannel. ");
socketChannel.close();
}
} catch (Exception e) {
// read , , socketChannel
e.printStackTrace();
p(selectionKeyDevice.attachment() + "socket closed? ");
socketChannel.close();
}
} else if (selectionKeyDevice.isWritable()) {
p(selectionKeyDevice.attachment() + "TODO: isWritable() ???????????????????????????? ");
} else if (selectionKeyDevice.isConnectable()) {
p(selectionKeyDevice.attachment() + "TODO: isConnectable() ????????????????????????? ");
} else {
p(selectionKeyDevice.attachment() + "TODO: else. ");
}
}
//
public void handleSelectionKey(SelectionKey selectionKey) throws Exception {
if (selectionKey.isAcceptable()) {
//
clientCount++;
ServerSocketChannel serverSocketChannel = (ServerSocketChannel) selectionKey.channel();
SocketChannel socketChannel = serverSocketChannel.accept();
socketChannel.configureBlocking(false);
Socket socket = socketChannel.socket();
System.out.println(serverSocketChannel.socket().getLocalSocketAddress());
// OP_READ SelectionKey,
SelectionKey key = socketChannel.register(selector, SelectionKey.OP_READ);
key.attach(" " + clientCount + " [" + socket.getRemoteSocketAddress() + "]: ");
p(key.attachment() + "\t[connected] =========================================");
} else if (selectionKey.isReadable()) {
//
ByteBuffer byteBuffer = ByteBuffer.allocate(100);
ByteBuffer byteBufferDD= ByteBuffer.allocate(100);
SocketChannel socketChannel = (SocketChannel) selectionKey.channel();
SocketChannel socketChannelDevice=(SocketChannel)map.get("/192.168.1.102").channel();
System.out.println(map.get("/192.168.1.102"));
//System.out.println(socketChannelDevice.socket().getPort());
try {
//
int instruction = socketChannel.read(byteBuffer);
int data=socketChannelDevice.read(byteBufferDD);
if (instruction > 0) {
byteBuffer.flip();//flip() , limit position , position 0
//socketChannel.write(byteBuffer);
socketChannelDevice.write(byteBuffer);
}
//
else if (data > 0)
{
byteBuffer.flip();
socketChannel.write(byteBuffer);
} else {
// , socketChannel
p(selectionKey.attachment() + "read finished. close socketChannel. ");
socketChannel.close();
}
} catch (Exception e) {
// read , , socketChannel
e.printStackTrace();
p(selectionKey.attachment() + "socket closed? ");
socketChannel.close();
}
} else if (selectionKey.isWritable()) {
p(selectionKey.attachment() + "TODO: isWritable() ???????????????????????????? ");
} else if (selectionKey.isConnectable()) {
p(selectionKey.attachment() + "TODO: isConnectable() ????????????????????????? ");
} else {
p(selectionKey.attachment() + "TODO: else. ");
}
}
public static void p(Object object) {
System.out.println(object);
}
public static void main(String[] args) throws Exception {
new myServer();
}
}
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Is Eclipse IDE dying?In 2014 the Eclipse IDE is the leading development environment for Java with a market share of approximately 65%. but ac...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.