티스토리 뷰

반응형

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");

	    }
	}

 

서버 구축 클래스

반응형
댓글
반응형
최근에 올라온 글
최근에 달린 댓글
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31