직접 사용 BIO, NIO, AIO 서버
9738 단어 네트워크 프로그래밍
1.BIO
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class BIOServer {
public static void main(String[] args) {
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(8080);
while (true){
Socket socket = serverSocket.accept();
ReadThread readThread = new ReadThread(socket);
readThread.start();
}
} catch (IOException e) {
e.printStackTrace();
}finally {
if (serverSocket != null){
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
private static class ReadThread extends Thread{
private Socket socket;
public ReadThread(Socket socket) {
this.socket = socket;
}
@Override
public void run() {
try {
InputStream in = socket.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String mes;
while ((mes = reader.readLine()) != null) {
System.out.println(mes);
}
socket.close();
}catch (IOException e) {
e.printStackTrace();
}
}
}
}
public class BIOServer {
public static void main(String[] args) {
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(8080);
while (true){
Socket socket = serverSocket.accept();
socket.setSoTimeout(5000); //
ReadThread readThread = new ReadThread(socket);
readThread.start();
}
} catch (IOException e) {
e.printStackTrace();
}finally {
if (serverSocket != null){
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
private static class ReadThread extends Thread{
private Socket socket;
public ReadThread(Socket socket) {
this.socket = socket;
}
@Override
public void run() {
try {
InputStream in = socket.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String mes;
while ((mes = reader.readLine()) != null) {
System.out.println(mes);
}
System.out.println("xxx");
socket.close();
}catch (SocketTimeoutException e) {
System.out.println(" , ....");
try {
socket.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}catch (IOException e){
e.printStackTrace();
}
}
}
}
2.NIO
여러 가지 형식이 있습니다. 다음은 Reactor 단일 스레드 모드입니다. 하나의 스레드로 요청을 받고 하나의 스레드로 IO 작업을 수행합니다.
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.nio.charset.Charset;
import java.util.Iterator;
import java.util.Set;
public class NIOServer {
private static final Charset charset = Charset.forName("utf-8");
private static Selector selector ;
static {
try {
selector = Selector.open();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
try {
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
InetSocketAddress address = new InetSocketAddress(8080);
serverSocketChannel.configureBlocking(false);
serverSocketChannel.bind(address);
serverSocketChannel.register(selector,SelectionKey.OP_ACCEPT);
new Reactor().start();
} catch (IOException e) {
e.printStackTrace();
}
}
private static class Reactor extends Thread{
@Override
public void run() {
try {
select();
} catch (IOException e) {
e.printStackTrace();
}
}
private void select() throws IOException{
while (selector.select()>0){ // , , CPU
Set selectionKeys = selector.selectedKeys();
Iterator iterator = selectionKeys.iterator();
while (iterator.hasNext()){
SelectionKey key = iterator.next();
if (key.isAcceptable()){
accept(key);
}else if (key.isReadable()){
read(key);
}
iterator.remove(); // !
}
}
}
private void read(SelectionKey key) throws IOException {
SocketChannel channel = (SocketChannel) key.channel();
ByteBuffer byteBuffer = ByteBuffer.allocate(100);
int num = channel.read(byteBuffer);
if (num > 0) {
byteBuffer.flip();
String data = charset.decode(byteBuffer).toString();
System.out.println(data);
}else if (num == -1){
// num=-1
channel.close();
}
}
private void accept(SelectionKey key) throws IOException {
ServerSocketChannel serverChannel = (ServerSocketChannel) key.channel();
SocketChannel channel = serverChannel.accept();
if (channel != null) {
InetSocketAddress localAddress = (InetSocketAddress) channel.getLocalAddress();
String hostName = localAddress.getHostName();
System.out.println(" " + hostName + " ");
channel.configureBlocking(false);
// socket
channel.register(selector, SelectionKey.OP_READ);
}
}
}
}
3.AIO
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
public class AIOServer {
public void startListen(int port) throws InterruptedException {
try {
AsynchronousServerSocketChannel serverSocketChannel = AsynchronousServerSocketChannel.open();
serverSocketChannel.bind(new InetSocketAddress(port));
serverSocketChannel.accept(null,new CompletionHandler() {
@Override
public void completed(AsynchronousSocketChannel socketChannel, Void attachment) {
serverSocketChannel.accept(null,this); // , accept
ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
socketChannel.read(byteBuffer,byteBuffer, new CompletionHandler() {
@Override
public void completed(Integer num, ByteBuffer attachment) {
if (num > 0){
attachment.flip();
System.out.println(new String(attachment.array()).trim());
}else {
try {
socketChannel.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Override
public void failed(Throwable exc, ByteBuffer attachment) {
System.out.println("read error");
exc.printStackTrace();
}
});
}
@Override
public void failed(Throwable exc, Void attachment) {
System.out.println("accept error");
exc.printStackTrace();
}
});
} catch (IOException e) {
e.printStackTrace();
}
//
while (true){
Thread.sleep(1000);
}
}
public static void main(String[] args) throws InterruptedException {
AIOServer aioServer = new AIOServer();
aioServer.startListen(8080);
}
}
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Java 네트워크 프로그래밍 기본 자습서의 Socket 시작 사례우리가 자바에서 TCP/IP를 사용하여 네트워크를 통해 서버에 연결하려면 자바를 만들어야 합니다.net.Socket 객체를 서버에 연결합니다.Java NIO를 사용하려는 경우 Java NIO의 SocketChanne...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.