티스토리 뷰
반응형
import java.net.*;
import java.util.*;
public class MultiServer{
ServerSocket sc; // 서버 소켓
Vector<Thread> clients; // 클라이언트 목록
ClientThread client; // 클라이언트 쓰레드
Iterator<Thread> clientsEn; // 클라이언트 목록 검색 : Enumeration
// Enumeration clientsEn;
// 메인 메소드
public static void main(String args[]){
MultiServer ms=null; // 채팅 서버 초기화
try {
ms=new MultiServer(); // 채팅서버 객체 생성
ms.welcomeClients(); // 메시징
} catch(Exception e){
System.out.println("main:"+e);
} // try
}
// 서버 소켓 초기화 : port !
public MultiServer() throws Exception{
sc=new ServerSocket(7777);
clients=new Vector<Thread>();
}
// 메시징(messaging) : 클라이언트가 접속(connection)하였을 때(accept)
// 접속에 대한 메시지를 전함. 클라이언트(누리꾼 : Thread)를 등록
public void welcomeClients() throws Exception{
while(true) {
Socket socket=sc.accept(); // 클라이언트의 소켓 접속을 승인(accept)
client=new ClientThread(socket, this);
addClient(client); // 클라이언트(채팅서버) 목록에 추가
client.setDaemon(true); // p.641
client.start(); // 쓰레드(클라이언트) 시작 : 누리꾼이 활동을 시작
}
}
// 클라이언트를 채팅서버의 목록에 추가
public synchronized void addClient(Thread clientThread){
clients.add(clientThread);
System.out.println("전체 클라이언트들 : "+clients.size() + "명");
}
//메시지를 균등하게(쓰레드 : 싱크로나이제이션) 전송[]
public synchronized void broadCast(String message){
clientsEn = clients.iterator();
while(clientsEn.hasNext())
((ClientThread)clientsEn.next()).sendMessage(message);
}
// 클라이언트(누리꾼) 목록 균등하게 전송
public void broadClientList(){
String re="";
for(Thread th : clients)
re +=((ClientThread)th).nickName+"|";
/*
for(int i=0; i<clients.size(); i++)
re+=((ClientThread)clients.get(i)).nickName+"|";
*/
re=re.substring(0,re.length()-1);
broadCast("001"+re); // 응답메시지를 균등하게 전송
}
// 채팅서버(목록)로부터 클라이언트(누리꾼)을 삭제
public synchronized void deleteFromServer(ClientThread clientThread){
clients.remove(clientThread);
System.out.println(clients.size()+" left in server");
}
}
서버 구축 클래스
반응형
'IT & programming > Java' 카테고리의 다른 글
| 8/23 - 채팅 소스, 채팅 클라이언트 부분 (0) | 2012.08.23 |
|---|---|
| 8/23 - 채팅 소스, 클라이언트 쓰레드 부분 (0) | 2012.08.23 |
| 8/22 - I/O, 스트림, IOEx 예제문제 (0) | 2012.08.22 |
| 8/21 - AWT, 로그인 예제, Adapter클래스 이용 (0) | 2012.08.21 |
| 8/20 - AWT, 로그인 창 예제 (0) | 2012.08.20 |
댓글