본문 바로가기
Java, JSP

Java ServerSocket Multithereading 예제

by 수앙 2016. 4. 25.

Java 1.4.2부터 NIO가 나와있지만

기본인 BIO 소켓 처리 예제를 다룬다.


사실 NIO 코딩이 더 어렵다.

채널, 바이트버퍼, 셀렉터 등등...

MINA나 Netty 프레임웍을 쓰면 좀 쉽게 처리가 가능하다.


아래는 BIO 소켓서버 처리 코드이다.


ServerSocket1.java

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

import java.io.OutputStreamWriter;

import java.io.PrintWriter;

import java.net.InetAddress;

import java.net.ServerSocket;

import java.net.Socket;

import java.util.concurrent.ExecutorService;

import java.util.concurrent.Executors;


public class ServerSocket1 {

private ExecutorService executorService = Executors.newFixedThreadPool(10);

private ServerSocket serverSocket;

public ServerSocket1() throws IOException {

InetAddress bindAddr = InetAddress.getByName("localhost");

System.out.println(bindAddr.getHostName() + " => " + bindAddr.getHostAddress());

// 포트는 8080, 접속 대기는 100

this.serverSocket = new ServerSocket(8080, 100, bindAddr);

}

public void run() {

try {

while (true) {

System.out.println("waiting..");

Socket socket = serverSocket.accept();

SocketProcess1 socketProcess1 = new SocketProcess1(socket);

executorService.execute(socketProcess1);

}

} catch (IOException e) {

e.printStackTrace();

} finally {

if (executorService != null) {

executorService.shutdown();

}

}

}

public void close() {

try {

if (serverSocket != null) {

serverSocket.close();

}

} catch (IOException e) {

e.printStackTrace();

}

}


public static void main(String[] args) {

ServerSocket1 serverSocket1 = null;

try {

serverSocket1 = new ServerSocket1();

serverSocket1.run();

} catch (IOException e) {

e.printStackTrace();

} finally {

serverSocket1.close();

}

}

}


class SocketProcess1 extends Thread {

private Socket socket;

private BufferedReader br;

private PrintWriter pw;


public SocketProcess1(Socket socket) throws IOException {

this.socket = socket;

br = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));

pw = new PrintWriter(new OutputStreamWriter(socket.getOutputStream(), "UTF-8"));

}

@Override

public void run() {

System.out.println("start..");

String line = null;

try {

while ((line = br.readLine()) != null) {

System.out.println(line);

pw.println(line);

}

} catch (IOException e) {

e.printStackTrace();

} finally {

if (pw != null) pw.close();

if (br != null) try { br.close(); } catch (IOException e) { }

if (socket != null) try { socket.close(); } catch (IOException e) { }

}

System.out.println("end..");

}

}


끝.

'Java, JSP' 카테고리의 다른 글

ThreadLocal(스레드로컬)  (0) 2016.08.16
Apahce poi 엑셀 읽기(파싱)  (0) 2016.07.31
Java 큐(Queue) 종류 및 특성  (0) 2016.03.30
Java return generic type (map to bean)  (0) 2015.06.12
Java Socket & ServerSocket options  (0) 2013.04.20

댓글