http://shssk09.tistory.com/5
이번에는 Thread를 이용하여 여러 클라이언트를 받을 수 있는 프로그램이다.
EchoServer.java EchoClient.java
/* implemet */
-EchoServer.java
import java.net.ServerSocket;
import java.net.Socket;
import java.io.PrintWriter;
import java.io.IOException;
import java.lang.Thread; //스레드를 사용한다.
import java.lang.InterruptedException; // implement this
public class EchoServer {
public static void main(String []args) {
try {
ServerSocket server = new ServerSocket(1234); // 서버소켓을 생성하는데 포튼넘버는 1234다.
int id = 0;
while(true) {
Socket client = server.accept(); // 클라이언트를 기다린다.
System.out.println("Spawning client " + id); //클라이언트가 접속한 것을 화면에 출력한다.
//접속한 클라이언트에 대해 스레드를 생성하는데, EchoServerHandler 클래스 객체에 대해 생성한다.
Thread clientThread = new Thread(new EchoServerHandler(client, id));
clientThread.start(); //위에서 생성한 스레드를 시작한다.
id ++;
}
}
catch(IOException e) {
e.printStackTrace();
}
}
}
/* 각 클라이언트를 담당할 클래스다.
클라이언트의 id와 소켓을 private변수로 가지고 있는다.*/
class EchoServerHandler extends Thread {
private int id;
private Socket client;
public EchoServerHandler(Socket socket, int i) {
client = socket;
id = i;
}
/* 스레드가 start()되면 run()함수를 실행시키게 되는데
클라이언트에게 스트림을 전송 할 스트림 핸들러를 생성한 뒤,
0~9999를 0.1초마다 클라이언트에게 전송한다. */
public void run() {
try {
PrintWriter writer = new PrintWriter(client.getOutputStream());
for(int i = 0; i < 10000; i++) {
writer.println("i = " + i);
System.out.println("Send client " + id + ", i = " + i);
this.sleep(10);
}
writer.close();
client.close();
}
catch(IOException e) {
e.printStackTrace();
}
catch(InterruptedException ie) {
ie.printStackTrace();
}
}
}
-EchoClient.java
import java.net.Socket;
import java.util.Scanner;
import java.io.IOException;
public class EchoClient {
public static void main(String []args) {
try {
Socket client = new Socket("localhost", 1234); // 소켓을 생성하여 서버에 연결한다. 포트넘버 : 1234
Scanner scanner = new Scanner(client.getInputStream()); //서버로부터 스트림을 읽기위한 핸들러
while (scanner.hasNextLine()) {
System.out.println(scanner.nextLine()); //읽어온 값을 화면으로 출력한다.
}
scanner.close();
client.close();
}
catch(IOException e) {
e.printStackTrace();
}
}
}
결과 :
서버 :
Send client 'id', i = 0~9999
클라이언트 :
i = 0~9999
'IT' 카테고리의 다른 글
cp1.c (0) | 2014.09.17 |
---|---|
who1.c (0) | 2014.09.17 |
java network programming (0) | 2014.08.30 |
핑테스트를 하자 [링크] (0) | 2014.08.28 |
DHT (0) | 2014.07.02 |