Socket Simple 채팅 프로그램

 | JAVA
2012. 5. 15. 18:35

서버

 

package kr.hun.mesange;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;

public class ServerMessinger {
    ArrayList<EachThread> clients=new ArrayList<EachThread>();

    public static void main(String[] args) {
        new ServerMessinger();
    }
    public ServerMessinger(){
        try {
           
            ServerSocket serverSocket= new ServerSocket(7777);
            System.out.println("nomally Server Turn ON");
           
           
            while (true) {
               
                Socket socket = serverSocket.accept();
                EachThread buff=new EachThread(socket);
                clients.add(buff);
                buff.start();
                System.out.println("client"+socket);
                   
            }
           
        } catch (Exception e) {
            // TODO: handle exception
        }
    }
   
    class EachThread extends Thread{
        Socket socket=null;
    public     DataInputStream dis = null;
    public     DataOutputStream dos = null;
       
       
        public EachThread(Socket socket){
            this.socket=socket;
        }
       
        public void run(){
           
           
            try {
                dis=new DataInputStream(socket.getInputStream());
                dos=new DataOutputStream(socket.getOutputStream());
               
                while (true) {
                    String msg=dis.readUTF();
                   
                    for(int i =0;i<clients.size();i++){
                        clients.get(i).dos.writeUTF(msg);
                    }
                   
                    if(msg.equals("exit")){
                        break;
                    }
                }
                clients.remove(this);
                System.out.println("exit by user's request ");
               
            } catch (Exception e) {
                // TODO Auto-generated catch block
                clients.remove(this);
                System.out.println("exit by system's error");
            }
       
       
        }
    }
   
}

클라이언트

package kr.hun.mesange;

import java.awt.EventQueue;

public class MessangerTest extends JFrame {
    public DataInputStream dis=null;
    public DataOutputStream dos=null;;
    private JPanel contentPane;
    private JTextField tfIP;
    private JScrollPane scrollPane;
    private JTextField tfword;
    private JTextField tfPORT;
   
    boolean connect =false;
    private JTextArea taResult;
   
    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    MessangerTest frame = new MessangerTest();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public MessangerTest() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 384, 547);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(null);
       
        JButton btnSocket = new JButton("\uC811\uC18D");
        btnSocket.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                btnSocketGo();
            }
        });
        btnSocket.setBounds(261, 15, 73, 44);
        contentPane.add(btnSocket);
       
        tfIP = new JTextField();
        tfIP.setText("127.0.0.1");
        tfIP.setBounds(90, 15, 159, 22);
        contentPane.add(tfIP);
        tfIP.setColumns(10);
       
        scrollPane = new JScrollPane();
        scrollPane.setViewportBorder(null);
        scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
        scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
        scrollPane.setBounds(12, 85, 340, 354);
        contentPane.add(scrollPane);
       
        taResult = new JTextArea();
        taResult.setEnabled(false);
        scrollPane.add(taResult);
        scrollPane.setViewportView(taResult);
       
       
       
        tfword = new JTextField();
        tfword.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
            if(e.getKeyCode()==10){
                btnWordSend();
            }
            }
        });
       
        tfword.setFont(new Font("굴림", Font.PLAIN, 15));
        tfword.setBounds(12, 449, 340, 30);
        contentPane.add(tfword);
        tfword.setColumns(10);
       
        tfPORT = new JTextField();
        tfPORT.setText("7777");
        tfPORT.setColumns(10);
        tfPORT.setBounds(90, 47, 159, 22);
        contentPane.add(tfPORT);
       
        JLabel lblIP = new JLabel("I P       :");
        lblIP.setBounds(12, 20, 57, 15);
        contentPane.add(lblIP);
       
        JLabel lblPort = new JLabel("PORT   :");
        lblPort.setBounds(12, 50, 57, 15);
        contentPane.add(lblPort);
       
       
       
    }
    public void btnWordSend(){
        if(connect==true){
       
            String msg=tfword.getText();
            tfword.setText("");
            try {
                dos.writeUTF("ID:sararing :: "+msg);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            if(msg.equals("exit"))System.exit(0);
        }else {
            tfword.setText("");
            taResult.append("서버에 접속 해야만 채팅이 가능 합니다. \n");
        }
       
    }
    public void btnSocketGo(){
        String str=tfIP.getText();

        int port = Integer.parseInt(tfPORT.getText());
       
        try {
           
            Socket socket = new Socket(str,port);
            taResult.append("서버에 성공적으로 접속되었습니다...\n");
           
            connect=true;
            dis=new DataInputStream(socket.getInputStream());
            dos=new DataOutputStream(socket.getOutputStream());
            new EachThread().start();


        } catch (Exception e) {
            taResult.append("서버가 작동 하지 않거나.\n IP,PORT 를 확인해주세요.\n ");
        }
    }

    class EachThread extends Thread{
        public void run(){
            while(true){
            try {
                String msg=    dis.readUTF();
                taResult.append(msg+"\n");
                taResult.setSelectionStart(taResult.getText().length());  // 스크롤펜이 내려 가면서 최신화 시켜서 밑에 줄에 위치 할수 있도록 한다.
               
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            }
        }
    }
}

이 글은 스프링노트에서 작성되었습니다.

'JAVA' 카테고리의 다른 글

간단 수식계산기  (0) 2012.05.15
String(문자열)내의 한글 확인  (0) 2012.05.15
SMS 보내기  (0) 2012.05.15
Printf 수식 모음  (0) 2012.05.15
passwd 암호화  (0) 2012.05.15
Posted by 사라링
BLOG main image
.. by 사라링

카테고리

사라링님의 노트 (301)
JSP (31)
J-Query (41)
JAVA (24)
디자인패턴 (1)
스트러츠 (3)
안드로이드 (11)
오라클 (45)
우분투-오라클 (1)
이클립스메뉴얼 (6)
스프링3.0 (23)
자바스크립트 (10)
HTML5.0 (17)
정보처리기사 (1)
기타(컴퓨터 관련) (1)
문제점 해결 (3)
프로젝트 (2)
AJAX (4)
하이버네이트 (3)
트러스트폼 (11)
Jeus (2)
재무관리(회계) (5)
정규식 (5)
아이바티스 (8)
취미 (2)
소프트웨어 보안 관련모음 (0)
정보보안기사 (6)
C언어 베이직 및 프로그램 (3)
보안 관련 용어 정리 (2)
넥사크로 (6)
웹스퀘어_ (0)
Total :
Today : Yesterday :