2011-07-02 6 views
0

방금 ​​첫 번째 서버/클라이언트 코드와 간단한 채팅 프로그램을 작성하기 시작했으나 코드를 어떻게 실행해야하는지 잘 모릅니다!서버/클라이언트 코드는 어떻게 실행해야합니까?

Server Side라는 이름의 .class 파일과 clientSide라는 .class 파일이 서로 다른 프로젝트에 있어야합니까? 둘 다 연결되어 있기 때문에 어떻게 실행해야합니까? 덕분에 이미, 다음은 코드

public void runServer() 
    { 
     try { 
      server = new ServerSocket(); 
      while(true) 
      { 
       try 
       { 
        connection = server.accept(); 
        try{ 
         output = new ObjectOutputStream(connection.getOutputStream()) ; 
         output.flush(); 
         input = new ObjectInputStream(connection.getInputStream()) ; 
         sendData(message) ; 
         do 
         { 
          try{ 
           message = (String) input.readObject() ; 
           System.out.println(message); 
          }catch(Exception e) 
          { 
           e.printStackTrace() ; 
          } 
         }while(!message.equals("end")); 
        }catch(EOFException e) 
        { 
         e.printStackTrace() ; 
        } 
       }catch(IOException e) 
       { 
        e.printStackTrace() ; 
       }   
       finally { 
        try{ 
        output.close(); 
        input.close(); 
        connection.close() ; 
        }catch(Exception e) 
        { 
         e.printStackTrace(); 
        } 
        } 
      } 
     }catch(Exception e) 
     { 
      e.printStackTrace(); 
     } 
    } 

을의 일부이며 여기에 클라이언트 측의 :

public void runClient() 
    { 
      try{ 
      connect() ; 
      }catch(Exception e) 
      { 
       e.printStackTrace(); 
      } 
      try{ 
       output = new ObjectOutputStream(client.getOutputStream()) ; 
       output.flush() ; 
       input = new ObjectInputStream(client.getInputStream()) ; 
      }catch(IOException e) 
      { 
       e.printStackTrace() ; 
      } 
      do 
      { 
       try{ 
        message = (String) input.readObject() ; 
        System.out.println(message); 
       }catch(Exception e) 
       {e.printStackTrace();} 
      }while(!message.equals("end")) ; 

    } 
    public void connect() throws UnknownHostException, IOException 
    { 
     client = new Socket(InetAddress.getByName(chatServer),12345) ; 
    } 

답변

1

먼저

자바 서버

그런 다음를 실행하는 서버를 실행 고객 :

자바 클라이언트

하지만 서버가 클라이언트 때문에 문의 포트 12345에서 서버에 연결을 시도합니다 포트 12345에 바인딩이 표시되지 않습니다

client = new Socket(InetAddress.getByName(chatServer),12345) ; 

하는 경우 포트가 일치하지 않으면 연결이 설정되지 않습니다.

는 포트 12345에 서버가이 시도에 바인딩하려면 대신 기본 생성자의

server = new ServerSocket(12345); 

합니다. 클라이언트와 서버 :

http://download.oracle.com/javase/tutorial/networking/sockets/clientServer.html

당신은 두 가지 패키지로이 개 파일을 클라이언트 서버 하나 하나를 수행해야합니다

0

는 모든 기술 한 아주 좋은 튜토리얼있다.

관련 문제