- [Java 기본] Java Network - MulticastSocket을 이용한 채팅/파일전송 프로그램

Posted by 겨울에
2011. 5. 14. 16:34 scrap/ Java/JSP
출처 : http://cafe.naver.com/litave/406





/**
* 과거에 MulticastSocket를 이용한 채팅 및 파일 전송 프로그램을 작성했던 내용입니다.
* 작성자 : litwave
*/
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
import java.io.*;
import java.net.*;

class MulticastChatting extends JFrame implements ActionListenerRunnable {
    
    private Container con;

    private FileInputStream fis = null;
    private FileOutputStream fos = null;
        
    // 받기위한 패킷, 소켓
    private DatagramPacket receivePacket;
    private MulticastSocket receiveSocket;
    
    // 보내기 위한 패킷, 소캣
    private DatagramPacket sendPacket;
    private MulticastSocket sendSocket;    

    //파일 다이얼 로그
    JFileChooser fd = new JFileChooser("./");
        
    // 화면 구성 멤버
    private JLabel idLb = new JLabel(" 아이디 "JLabel.RIGHT);
    private JTextField idTf = new JTextField(15);
    private JTextArea showTa = new JTextArea();
    private JScrollPane showJsp = new JScrollPane(showTa);
    private JLabel sendMsgLb = new JLabel(" 메제지 "JLabel.RIGHT);
    private JTextField sendMsgTf = new JTextField();
    private JButton sendFileBt = new JButton(" 파일전송 ");
    private JButton exitBt = new JButton(" 종료 ");
    
    // Border 선언
    private Border btB = BorderFactory.createRaisedBevelBorder();
    private Border tfB = new BevelBorder(BevelBorder.LOWERED);
    
    //new BevelBorder(BevelBorder.RAISED);
    // 배경색
    private Color bgColor = new Color(255242242);
    // JLabel 글꼴 지정
    private Font lbFont = new Font("새굴림"Font.BOLD16);
    private Color lbTextColor = new Color(17289255);
    //JButton 모양 설정
    private Font btFont = new Font("HY엽서L"014);
    private Color btTextColor = new Color(225225225);
    private Color btBgColor = new Color(00160);
    
    //텍스트 필드 설정
    private Color tfBgColor = new Color(255255230);
    private Color tfTextColor = new Color(00128);
    private Font tfFont = new Font("HY중고딕"012);
    
    public void initComponent() {
        idLb.setFont(lbFont);
        sendMsgLb.setFont(lbFont);
        idLb.setForeground(lbTextColor);
        sendMsgLb.setForeground(lbTextColor);
        
        idTf.setFont(tfFont);
        idTf.setForeground(tfTextColor);
        idTf.setBackground(tfBgColor);
        idTf.setBorder(tfB);
        sendMsgTf.setFont(tfFont);
        sendMsgTf.setForeground(tfTextColor);
        sendMsgTf.setBackground(tfBgColor);
        sendMsgTf.setBorder(tfB);

        showTa.setBackground(new Color(244255244));
        showTa.setForeground(new Color(00128));

        sendFileBt.setFont(btFont);
        sendFileBt.setForeground(btTextColor);
        sendFileBt.setBackground(btBgColor);
        sendFileBt.setBorder(btB);
        exitBt.setFont(btFont);
        exitBt.setForeground(btTextColor);
        exitBt.setBackground(btBgColor); exitBt.setBorder(btB); } public MulticastChatting() {
        super("Multicast Sample Messenger v0.3");
        init();
        start();
        setSize(300400);
        Toolkit tk = Toolkit.getDefaultToolkit();
        Dimension d1 = tk.getScreenSize();
        Dimension d2 = this.getSize();
        this.setLocation((int)(d1.getWidth()/2-d2.getWidth()/2), 
                    (int)(d1.getHeight()/2-d2.getHeight()/2));
        setVisible(true);
    }
    
    public void init() {
        con = this.getContentPane();
        con.setLayout(new BorderLayout(5,5));

        JPanel jPn1 = new JPanel(new BorderLayout(5,5));
        jPn1.add("West", idLb);
        jPn1.add("Center", idTf);
        con.add("North", jPn1);
        
        con.add("Center", showJsp);
        
        JPanel jPn3 = new JPanel(new BorderLayout(5,5));
        jPn3.add("West", sendMsgLb);
        jPn3.add("Center", sendMsgTf);
            JPanel jPn31 = new JPanel(new GridLayout(1,2));
            jPn31.add(sendFileBt);
            jPn31.add(exitBt);
        jPn3.add("South", jPn31);
        con.add("South", jPn3);

        initComponent();
        con.setBackground(bgColor);
        jPn1.setBackground(bgColor);
        jPn3.setBackground(bgColor);
        jPn31.setBackground(bgColor);
        
        showTa.setEnabled(false);
        idTf.requestFocus();
        
        // down 디렉토리 생성
        File f = new File("./down");
        if(!f.exists()) {
            System.out.println("파일 생성 : " + f.mkdir());
        }
    }
    
    public void start() {
        idTf.addActionListenerthis );
        sendMsgTf.addActionListenerthis );
        sendFileBt.addActionListenerthis );
        exitBt.addActionListenerthis );
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }
    
    public void run() {
        showTa.setText("##### 대화방에 입장하셨습니다. #####\n");
        try {
            receiveSocket = new MulticastSocket(20000);
            receiveSocket.joinGroup(InetAddress.getByName("239.2.3.4"));
        } catch (IOException ex) { }
        
        String fileName = null;
        while(true) {
            receivePacket = new DatagramPacket(new byte[1024], 1024);
            try{
                receiveSocket.receive(receivePacket);
            } catch (IOException ex) { }
            
            byte[] data = receivePacket.getData();
            String protocal = new String(data, 06);
            
            if(protocal.equals("[MESG]")) {
                showTa.append((new String(data, 61018).trim()) + "\n");
            // 새로운 파일을 열음
            } else if(protocal.equals("[SFNE]")) {
                try {
                    fileName = new String(data, 61018).trim();
                    if(fileName != null)
                        fos = new FileOutputStream(".\\down\\" + fileName);
                } catch(FileNotFoundException ex) {
                    ex.printStackTrace();
                }
            } else if(protocal.equals("[SFIL]")) {
                try{
                    fos.write(data, 8, (int)data[6* 100 + data[7]);
                } catch (IOException ex) { 
                    ex.printStackTrace();
                }
                if((int)data[6* 100 + data[7] < 1016) {
                    try {
                        if(fos != null) fos.close();
                        showTa.append(fileName + " 파일을 전송 받았습니다.\n");
                    } catch (IOException ex) { 
                        ex.printStackTrace();
                    }
                }
            }
            showTa.setCaretPosition(showTa.getText().trim().length());
        }
    }
    
    public void actionPerformed(ActionEvent ev) {
        if(ev.getSource() == idTf) {
            new Thread(this).start();
            idTf.setEnabled(false);
            sendMsgTf.requestFocus();
        } else if(ev.getSource() == sendMsgTf) {
            String str = sendMsgTf.getText().trim(); // 전송될 메세지
            if(str == null || str.length() == 0) {
                sendMsgTf.setText("");
                sendMsgTf.requestFocus();
                return;
            }
            
            str = idTf.getText().trim() + " >> " + str;
            
            // 메세지 전송 프로토콜을 삽입
            str = "[MESG]" + str;
            
            sendBytes(str.getBytes());
            
            sendMsgTf.setText("");
            sendMsgTf.requestFocus();
        
        } else if(ev.getSource() == exitBt) {
            System.exit(0);
        } else if(ev.getSource() == sendFileBt) {
            fd.setDialogTitle("전송할 파일을 선택하세요!!");
            fd.showOpenDialog(this);
            if(fd.getSelectedFile() == null || fd.getSelectedFile().getName().length() == 0) {
                showTa.append("전송할 파일을 선택해야 합니다.!!\n");
                showTa.setCaretPosition(showTa.getText().trim().length());
                return;
            }
            showTa.append(fd.getSelectedFile().getName() + "파일을 전송합니다.\n");
            showTa.setCaretPosition(showTa.getText().trim().length());

            // 파일 이름 전송(with protocal)
            String str = "[SFNE]" + fd.getSelectedFile().getName(); // 전송될 파일이름
            sendBytes(str.getBytes());    // 파일 이름 전송
            
            byte[] strData = "[SFIL]".getBytes();    // 파일 보내기 Protocal 이름
            byte[] data = new byte[1024];
            
            for(int i=0; i<6; i++
                data[i] = strData[i];
            
            
            int testInt;
            try {
                fis = new FileInputStream(fd.getSelectedFile());
                while(true) {
                    testInt = fis.read(data, 81024-8);
                    if(testInt == -1break;
                    
                    // data에 읽어온 데이타의 길이를 data[6], data[7]에 나눠서 넣음
                    data[6] = (byte)(testInt / 100);
                    data[7] = (byte)(testInt % 100);
                
                    sendBytes(data);
                }
            } catch (FileNotFoundException ex) {
                
            } catch (IOException ex) {
                
            } finally {
                try {
                    if(fis != null) fis.close();
                } catch (IOException ex) { }
                showTa.append("파일 전송 완료!!..\n");
            }
            showTa.setCaretPosition(showTa.getText().trim().length());
        }
    }

    // 바이트 배열을 전송 시킨다.
    public void sendBytes(byte[] data) {
        // 데이터 전송
        // 1.데이타그램 패킷 생성
        try {
            sendPacket = new DatagramPacket(data, data.lengthInetAddress.getByName("239.2.3.4"), 20000);
        } catch (Exception ex) { }
        
        //2. 멀티캐스트 소캣 생성
        try {
            sendSocket = new MulticastSocket();
            sendSocket.setTimeToLive((byte)1);
            sendSocket.send(sendPacket);
            sendSocket.close();
        } catch(IOException ex) { }
    }    
}

public class MulticastChattingDemo {
    public static void main(String [] ar) {
        new MulticastChatting();
    }
}


 

'scrap >  Java/JSP' 카테고리의 다른 글

- [링크] The volatile keyword in Java  (0) 2011.05.14
- [Java 기본] JDBC를 이용한 Oracle 연동  (0) 2011.05.14
- [Java 기본] Java Network  (0) 2011.05.14
- [Java 기본]Swing  (0) 2011.05.14
- [Java 기본] JAVA File I/O  (0) 2011.05.14