티스토리 뷰

휴지통/Java

Client

LeReve 2013. 3. 11. 12:33

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.EOFException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.Socket;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;


public class Client extends JFrame{
 private JTextField enterField; // 사용자로부터 정보를 입력받음
 private JTextArea displayArea; // 사용자에게 정보를 보여줌
 private ObjectOutputStream output; // 서버에 보낼 출력 스트림
 private ObjectInputStream input; // 서버로부터 받을 입력 스트림
 private String message = ""; // 서버에서 받은 메시지
 private String chatServer; // 애플리케이션의 호스트 서버
 private Socket client; // 서버와 통신하는 소켓
 
 // 채팅 서버를 초기화 하고 GUI를 설정함
 public Client(String host){
  super("Client");
  
  chatServer = host; // 클라이언트가 연결할 서버를 설정함
  
  enterField = new JTextField(); // enterField를 생성함
  enterField.setEditable(false);
  enterField.addActionListener(
    new ActionListener() {
     // 서버에 메시지를 보냄
     @Override
     public void actionPerformed(ActionEvent event) {
      // TODO Auto-generated method stub
      sendData(event.getActionCommand());
      enterField.setText("");
     } // actionPerformed 메소드 끝
    } // 익명 내부 클래스
  ); // addActionListener 호출 끝
  
  add(enterField, BorderLayout.NORTH);
  displayArea=new JTextArea(); // displayArea를 생성함
  add( new JScrollPane(displayArea), BorderLayout.CENTER);
  
  setSize(300,150); // 윈도의 크기를 설정함
  setVisible(true); // 윈도를 표시함
 } // Client 생성자 끝
 
 // 서버에 연결하고 서버로부터 받은 메시지를 처리함
 public void runClient(){
  try{ // 서버에 연결해서 스트림을 얻어오고 연결을 처리함
   connectToServer(); // 연결을 위한 소켓을 생성함
   getStreams(); // 입출력 스트림을 얻어옴
   processConnection(); // 연결을 처리함
  } // try 블록 끝
  catch(EOFException eofException){
   displayMessage("\nClient terminated connection");
  } // catch 블록 끝
  catch(IOException ioException){
   ioException.printStackTrace();
  } // catch 블록 끝
  finally{
   closeConnection(); // 연결을 끊음
  } // finally 블록 끝
 } // runClient 메소드 끝
  
 // 서버에 연결함
 private void connectToServer() throws IOException{
  displayMessage("Attempting connection\n");
  
  // 서버와 연결할 소켓을 생성함
  client = new Socket(InetAddress.getByName(chatServer), 12345);
  
  // 연결 정보를 표시함
  displayMessage("Connected to: " + client.getInetAddress().getHostName());
 } // connectToServer 메소드 끝
 
 //데이터를 주고 받을 스트림을 얻음
 private void getStreams() throws IOException{
  // 객체에 대한 출력 스트림을 설정함
  output = new ObjectOutputStream(client.getOutputStream());
  output.flush(); // 헤더 정보를 보내기 위해 출력 버퍼를 비움
  
  // 객체에 대한 입력 스트림을 설정함
  input = new ObjectInputStream(client.getInputStream());
  displayMessage("\nGot I/O streams\n");
 } // getStreams 메소드 끝
 
 // 서버와의 연결을 처리함
 private void processConnection() throws IOException{
  // enterField를 활성화해서 클라이언트 사용자가 메시지를 보낼 수 있게 함
  setTextFieldEditable(true);
  
  do{ // 서버에서 받은 메시지를 처리함
   try{ // 메시지를 읽어서 표시함
    message = (String) input.readObject(); // 새로운 메시지를 읽음
    displayMessage("\n" + message ); // 메시지를 표시함
   } // try 블록 끝
   catch(ClassNotFoundException classNotFoundException){
    displayMessage("\nUnknown object type received");
   } // catch 블록 끝
  } while(!message.equals("SERVER>>> TERMINATE"));   
 } // processConnection 메소드 끝
 
 // 스트림과 소켓을 닫음
 private void closeConnection(){
  displayMessage("\nClosing connection");
  setTextFieldEditable(false); // enterField를 비활성화함
  
  try{
   output.close(); // 출력 스트림을 닫음
   input.close(); // 입력 스트림을 닫음
   client.close(); // 소켓을 닫음
  } // try 블록 끝
  catch(IOException ioException){
   ioException.printStackTrace();
  } // catch 블록 끝
 } // closeConnection 메소드 끝
 
 // 서버에 메시지를 보냄
 private void sendData( String message){
  try{ // 서버에 객체를 보냄
   output.writeObject("CLIENT>>> " + message);
   output.flush(); // 출력을 위해 데이터를 비움
   displayMessage("\nCLIENT>>> " + message);
  } // try 블록 끝
  catch(IOException ioException){
   displayArea.append("\nError writing object");
  } // catch 블록 끝
 } // sendData 메소드 끝
 
 // 이벤트 전달 스레드에 있는 displayArea를 조작함
 private void displayMessage(final String messageToDisplay){
  SwingUtilities.invokeLater(
    new Runnable() {
     
     @Override
     public void run() { // displayArea를 갱신함
      // TODO Auto-generated method stub
      displayArea.append(messageToDisplay);
     } // run 메소드 끝
    } // 익명 내부 클래스 끝
  ); //SwingUtilities.invokeLater 호출 끝
 } // displayMessage 메소드 끝
 
 //이벤트 전달 스레드에 있는 enterField를 조작함
 private void setTextFieldEditable(final boolean editable){
  SwingUtilities.invokeLater(
    new Runnable() {
     @Override
     public void run() { // enterField가 편집이 가능 여부를 설정함
      // TODO Auto-generated method stub
      enterField.setEditable(editable);
     } // run 메소드 끝
    } // 익명 내부 클래스 끝
  ); // SwingUtilities.invokeLater 호출 끝
 } // setTextFieldEditable 메소드 끝
} // Client 클래스 끝

'휴지통 > Java' 카테고리의 다른 글

자바 기초  (0) 2013.05.27
JDBC  (0) 2013.05.14
Client Test  (0) 2013.03.11
Server Test  (0) 2013.03.11
Server  (0) 2013.03.11
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
TAG
more
«   2025/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
글 보관함