2014년 1월 21일 화요일

Socket을 이용한 채팅 프로그램 소스[재직자무료교육/프로그래머교육/구로디지털IT교육,오라클/자바/닷넷/C#/iOS/안드로이드/아이폰교육]

Socket을 이용한 채팅 프로그램 소스[재직자무료교육/프로그래머교육/구로디지털IT교육,오라클/자바/닷넷/C#/iOS/안드로이드/아이폰교육]

TCP/IP Socket기반의 자바 채팅 프로그램 소스 입니다. Java Network Programming, Second Edition에 나오는 소스죠.

[ChatServer.java]


import java.io.*;
import java.net.*;
import java.util.*;

public class ChatServer {
  public static void main (String args[]) throws IOException {
    if (args.length != 1)
      throw new IllegalArgumentException ("Syntax: ChatServer < port>");
    int port = Integer.parseInt (args[0]);
    ServerSocket server = new ServerSocket (port);
    while (true) {
      Socket client = server.accept ();
      System.out.println ("Accepted from " + client.getInetAddress ());
      ChatHandler handler = new ChatHandler (client);
      handler.start ();
    }
  }
}



[ChatHandler.java]
import java.io.*;
import java.net.*;
import java.util.*;

public class ChatHandler implements Runnable {
  protected Socket socket;
  
  public ChatHandler (Socket socket) {
    this.socket = socket;
  }

  protected DataInputStream dataIn;
  protected DataOutputStream dataOut;
  protected Thread listener;
  
  public synchronized void start () {
    if (listener == null) {
      try {
        dataIn = new DataInputStream
          (new BufferedInputStream (socket.getInputStream ()));
        dataOut = new DataOutputStream
          (new BufferedOutputStream (socket.getOutputStream ()));
        listener = new Thread (this);
        listener.start ();
      } catch (IOException ignored) {
      }
    }
  }

  public synchronized void stop () {
    if (listener != null) {
      try {
        if (listener != Thread.currentThread ())
          listener.interrupt ();
        listener = null;
        dataOut.close ();
      } catch (IOException ignored) {
      }
    }
  }

  protected static Vector handlers = new Vector ();
  
  public void run () {
    try {
      handlers.addElement (this);
      while (!Thread.interrupted ()) {
        String message = dataIn.readUTF ();
        broadcast (message);
      }
    } catch (EOFException ignored) {
    } catch (IOException ex) {
      if (listener == Thread.currentThread ())
        ex.printStackTrace ();
    } finally {
      handlers.removeElement (this);
    }
    stop ();
  }

  protected void broadcast (String message) {
    synchronized (handlers) {
      Enumeration enum = handlers.elements ();
      while (enum.hasMoreElements ()) {
        ChatHandler handler = (ChatHandler) enum.nextElement ();
        try {
          handler.dataOut.writeUTF (message);
          handler.dataOut.flush ();
        } catch (IOException ex) {
          handler.stop ();
        }
      }
    }
  }
}





[ChatClient.java]
import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;

public class ChatClient implements Runnable, WindowListener, ActionListener {
  protected String host;
  protected int port;
  protected Frame frame;
  protected TextArea output;
  protected TextField input;
  
  public ChatClient (String host, int port) {
    this.host = host;
    this.port = port;
    frame = new Frame ("ChatClient [" + host + ':' + port + "]");
    frame.addWindowListener (this);
    output = new TextArea ();
    output.setEditable (false);
    input = new TextField ();
    input.addActionListener (this);
    frame.add ("Center", output);
    frame.add ("South", input);
    frame.pack ();
  }

  protected DataInputStream dataIn;
  protected DataOutputStream dataOut;
  protected Thread listener;
  
  public synchronized void start () throws IOException {
    if (listener == null) {
      Socket socket = new Socket (host, port);
      try {
        dataIn = new DataInputStream
          (new BufferedInputStream (socket.getInputStream ()));
        dataOut = new DataOutputStream
          (new BufferedOutputStream (socket.getOutputStream ()));
      } catch (IOException ex) {
        socket.close ();
        throw ex;
      }
      listener = new Thread (this);
      listener.start ();
      frame.setVisible (true);
    }
  }

  public synchronized void stop () throws IOException {
    frame.setVisible (false);
    if (listener != null) {
      listener.interrupt ();
      listener = null;
      dataOut.close ();
    }
  }

  public void run () {
    try {
      while (!Thread.interrupted ()) {
        String line = dataIn.readUTF ();
        output.append (line + "\n");
      }
    } catch (IOException ex) {
      handleIOException (ex);
    }
  }

  protected synchronized void handleIOException (IOException ex) {
    if (listener != null) {
      output.append (ex + "\n");
      input.setVisible (false);
      frame.validate ();
      if (listener != Thread.currentThread ())
        listener.interrupt ();
      listener = null;
      try {
        dataOut.close ();
      } catch (IOException ignored) {
      }
    }
  }

  public void windowOpened (WindowEvent event) {
    input.requestFocus ();
  }

  public void windowClosing (WindowEvent event) {
    try {
      stop ();
    } catch (IOException ex) {
      ex.printStackTrace ();
    }
  }

  public void windowClosed (WindowEvent event) {}
  public void windowIconified (WindowEvent event) {}
  public void windowDeiconified (WindowEvent event) {}
  public void windowActivated (WindowEvent event) {}
  public void windowDeactivated (WindowEvent event) {}

  public void actionPerformed (ActionEvent event) {
    try {
      input.selectAll ();
      dataOut.writeUTF (event.getActionCommand ());
      dataOut.flush ();
    } catch (IOException ex) {
      handleIOException (ex);
    }
  }

  public static void main (String[] args) throws IOException {
    if ((args.length != 1) || (args[0].indexOf (':') < 0))
      throw new IllegalArgumentException ("Syntax: ChatClient < host>:<port>");
    int idx = args[0].indexOf (':');
    String host = args[0].substring (0, idx);
    int port = Integer.parseInt (args[0].substring (idx + 1));
    ChatClient client = new ChatClient (host, port);
    client.start ();
  }
}


 


  • 자바
  • 오라클/빅데이터
  • 아이폰/안드로이드
  • 닷넷/WPF
  • 표준웹/HTML5
  • 채용/취업무료교육
  • 초보자코스

  • 댓글 없음:

    댓글 쓰기