JAVA

Socket Simple 채팅 프로그램

사라링 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();
            }
            }
        }
    }
}

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