주석 설명및 실행 목적에 대해 알켜주세요
엘보어
제가아는 내용만 했는데요 나머지 좀 부탁드립니다.
import java.net.*; //네트워크 통신
import java.io.*; //입출력
public class ChatServer extends Thread {
protected final static int DEFAULTPORT=5000;
protected int portNum;
protected java.util.Vector clientVector; // clientVector를 전역변수로 사용
protected ServerSocket server;
public ChatServer() {
this(DEFAULTPORT); // 바로 밑에 있는 메소드(생성자 : ChatServer(int port))를 호출한 , 매개변수의 값은 5000임
}
public ChatServer(int port) {
portNum = port;
clientVector = new java.util.Vector(); // 배열을 선언
try {
server = new ServerSocket(port); // 서버 소켓 생성
} catch(IOException ex) {
System.out.println(ChatServer 클래스를 실행할 수 없습니다.);
ex.printStackTrace();
System.exit(1);
}
}
public void run() {
try {
System.out.println(서버 시작);
while(true) {
Socket client = server.accept(); // 클라이언트의 연결을 기다린다.
ChatProcessor cp = new ChatProcessor(client, this);
cp.start(); // ChatProcessor 클래스내의 run() 실행,, Thread 생성/실행
synchronized(clientVector) {
clientVector.addElement(cp); // 벡터 배열 clientVector에 Thread 첨가, 클래스 cp 첨가
}
}
} catch(IOException ex) {
System.out.println(클라이언트와 연결되지 않는 경우 에러가 발생!!!);
System.exit(1);
}
}
public static void main(String[] args) {
int port = -1;
if ( args.length == 0 ) { // 실행할때 매개 변수가 없을 경우
new ChatServer().start(); // 포트 5000을 사용하여 서버를 실행. 즉, ChatServer 클래스내의 run() 실행
} else if ( args.length == 1 ) {
try {
port = Integer.parseInt(args[0]); // 문자열을 정수형 숫자로 변환(포트번호)
new ChatServer(port).start(); // 서버를 실행. 즉, ChatServer 클래스내의 run() 실행
} catch(NumberFormatException ex) {
System.out.println(포트 번호가 잘못 됐습니다.);
}
}
}
}
class ChatProcessor extends Thread {
protected ChatServer server;
protected Socket socket;
protected BufferedReader is;
protected PrintWriter os;
public ChatProcessor(Socket socket, ChatServer server) {
this.server = server;
this.socket = socket;
&nbnbsp;
try {
is = new BufferedReader(new InputStreamReader(socket.getInputStream()));
os = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()), true);
} catch(IOException ex) {
System.out.println(입출력 스트림을 열 때 에러가 발생하였습니다.);
}
}
public void run() {
try {
String message;
while(true) {
message = is.readLine(); // 사용자가 입력한 메시지를 읽어서
if (message != null)
sendToAll(message); // 다른 모든 사용자들에게 전달
else return;
}
} catch(IOException ex) {
// 예외 처리를 하지 않는다. 즉 생략.......
} finally {
try {
server.clientVector.removeElement(this); // 사용자가 채팅방을 나가면 이 부분이 수행됨..
is.close();
os.close();
socket.close();
} catch(IOException ex) {
System.out.println(소켓을 닫는 동안 에러가 발생하였습니다.);
}
}
}
public void sendToOne(String s) {
os.println(s);
}
public void sendToAll(String s) {
int clientNumber = server.clientVector.size(); // 사용중인 사용자의 수를 계산
for (int i=0;iclientNumber;i++) {
ChatProcessor cp = (ChatProcessor)server.clientVector.elementAt(i);
cp.sendToOne(s);
}
}
}