자바 Socket 을 이용 하여 채 팅 방 기능 인 스 턴 스 실현

최근 자바 socket 통신 기 초 를 연구 하여 코드 를 이용 하여 간단 한 다 중 채 팅 방 기능 을 실현 하 였 으 며,현재 코드 를 공유 하여 관심 있 는 사람 에 게 도움 이 되 기 를 바 랍 니 다.
디 렉 터 리 구조:

ChatClient:

package com.panda.chat; 
 
import java.awt.*; 
import java.awt.event.*; 
import java.io.*; 
import java.net.*; 
 
@SuppressWarnings("serial") 
public class ChatClient extends Frame { 
 private TextArea ta = new TextArea(); 
 private TextField tf = new TextField(); 
 private DataOutputStream dos = null; 
 private DataInputStream dis = null; 
 private Socket socket = null; 
 private boolean bConnected = false; 
 private Thread thread=null; 
 public static void main(String[] args) { 
  new ChatClient().frameClient(); 
 } 
 public void frameClient(){ 
  setSize(400, 400); 
  setLocation(400,300); 
  add(ta,BorderLayout.NORTH); 
  add(tf,BorderLayout.SOUTH); 
  pack(); 
  tf.addActionListener(new TfListener()); 
  //         
  this.addWindowListener(new WindowAdapter() { 
   @Override 
   public void windowClosing(WindowEvent e) { 
    disconnected(); 
    System.exit(0); 
   } 
  }); 
  this.connect(); 
  setVisible(true); 
 } 
 //        
 private void connect(){ 
  try { 
   socket = new Socket("127.0.0.1", 8888); 
   thread=new Thread(new ChatThread()); 
   thread.start(); 
   dos = new DataOutputStream(socket.getOutputStream()); 
   dis = new DataInputStream(socket.getInputStream()); 
  } catch (UnknownHostException e) { 
   // TODO Auto-generated catch block 
   e.printStackTrace(); 
  } catch (IOException e) { 
   // TODO Auto-generated catch block 
   e.printStackTrace(); 
  } 
 } 
 //     
 private void disconnected(){ 
  bConnected = false; 
  try { 
   dos.close(); 
   dis.close(); 
   socket.close(); 
  } catch (IOException e1) { 
   // TODO Auto-generated catch block 
   e1.printStackTrace(); 
  } 
 } 
 //       
 private class TfListener implements ActionListener{ 
 
  @Override 
  public void actionPerformed(ActionEvent e) { 
   String strMsg = tf.getText(); 
   tf.setText(""); 
   try { 
    dos.writeUTF(strMsg); 
    dos.flush(); 
   } catch (IOException e1) { 
    // TODO Auto-generated catch block 
    e1.printStackTrace(); 
   } 
  } 
   
 } 
 //            
 private class ChatThread implements Runnable{ 
  @Override 
  public void run() { 
   try { 
    bConnected = true; 
    while(bConnected){ 
     String msg = dis.readUTF(); 
     String taText = ta.getText(); 
     ta.setText(taText+msg+"
"); } } catch (SocketException e) { System.out.println(" ");; } catch (IOException e) { e.printStackTrace(); } } } }
ChatServer:

package com.panda.chat; 
 
import java.io.*; 
import java.net.*; 
import java.util.*; 
 
public class ChatServer { 
 private boolean started = false; 
 private List<ChatThread> chatThreads = new ArrayList<ChatThread>(); 
 public static void main(String[] args) { 
  new ChatServer().startServer(); 
 } 
 private void startServer(){ 
  try { 
   //     Socket 
   ServerSocket seso = new ServerSocket(8888); 
   started = true; 
   while(started){ 
    //          
    Socket sos = seso.accept(); 
    System.out.println("        "); 
    //            
    ChatThread ct = new ChatThread(sos); 
    chatThreads.add(ct); 
    new Thread(ct).start(); 
   } 
  } catch (IOException e) { 
   e.printStackTrace(); 
  } 
 } 
 private class ChatThread implements Runnable{ 
  private Socket socket; 
  private DataInputStream din=null; 
  private DataOutputStream don=null; 
  private boolean bConnected = false; 
  public ChatThread(Socket socket) { 
   super(); 
   this.socket = socket; 
  } 
  //        
  private void send(String strMsgIn){ 
   try{ 
    don.writeUTF(strMsgIn); 
    don.flush(); 
   }catch(IOException e){ 
    e.printStackTrace(); 
   } 
  } 
  @Override 
  public void run() { 
   try{ 
    din = new DataInputStream(socket.getInputStream()); 
    don = new DataOutputStream(socket.getOutputStream()); 
    //     
    bConnected = true; 
    while(bConnected){ 
     String strMsgIn = din.readUTF(); 
     System.out.println(strMsgIn); 
     //               
     for(int i =0;i<chatThreads.size();i++){ 
      chatThreads.get(i).send(strMsgIn); 
     } 
    } 
   }catch (IOException e) { 
    try { 
     //          ,      ,   List       
     socket.close(); 
     chatThreads.remove(this); 
    } catch (IOException e1) { 
     // TODO Auto-generated catch block 
     e1.printStackTrace(); 
    } 
   } finally{ 
    try { 
     din.close(); 
     don.close(); 
     socket.close(); 
    } catch (IOException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 
   } 
  } 
  
 } 
} 
ChatSever 를 실행 한 후 ChatClient 를 여러 번 동시에 열 면 여러 사람의 채 팅 을 실현 할 수 있 습 니 다.당신 도 해 보 세 요.

이상 이 바로 본 고의 모든 내용 입 니 다.여러분 의 학습 에 도움 이 되 고 저 희 를 많이 응원 해 주 셨 으 면 좋 겠 습 니 다.

좋은 웹페이지 즐겨찾기