'Java'에 해당되는 글 84건

  1. 2014.12.30 Multi Chatting
  2. 2014.12.29 Socket 통신으로 Image전송
  3. 2014.12.28 KeyListener
  4. 2014.12.26 ArrayList
  5. 2014.12.26 ChatClient
  6. 2014.12.26 OutputStream
  7. 2014.12.26 InputStream
  8. 2014.12.25 DataInputStream / DataOutputStream
  9. 2014.12.25 Finding IP using the domain name
  10. 2014.12.25 Multi Chatting
2014. 12. 30. 08:54
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

package Multi;

public class ChatProtocol {
    public static final String ID="ID";
   
    public static final String CHAT="CHAT";
   
    public static final String CHATALL="CHATALL";
   
    public static final String MESSAGE="MESSAGE";
   
    public static final String CHATLIST="CHATLIST";
}



======================




package Multi;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Vector;


public class ChatServer {

    Vector<ClientThread> vc;

    public ChatServer() {
        vc = new Vector<ClientThread>();
        ServerSocket server = null;
        try {
            server = new ServerSocket(8008);
        } catch (Exception e) {
            System.err.println("Error in ChatServer2");
            e.printStackTrace();
            System.exit(1);// 1은 비정상적인 종료
        }
        System.out.println("************************");
        System.out.println("클라이언트의 접속을 기다리고 있습니다.");
        System.out.println("************************");
        try {
            while (true) {
                Socket sock = server.accept();
                ClientThread ct = new ClientThread(sock);
                ct.start();
                vc.add(ct);
            }
        } catch (Exception e) {
            System.err.println("Error in Socket");
            e.printStackTrace();
            System.exit(1);
        }
    }

    // 접속된 모든 Client에게 메세지 전송
    public void sendAllClient(String msg) {
        for (int i = 0; i < vc.size(); i++) {
            ClientThread ct = vc.get(i);
            ct.sendMessage(msg);
        }
    }

    // Vector에서 ClientThread를 제거
    public void removeClient(ClientThread ct) {
        vc.remove(ct);
    }

    class ClientThread extends Thread {
        Socket sock;
        BufferedReader in;
        PrintWriter out;
        String id = "익명";

        public ClientThread(Socket sock) {
            this.sock = sock;
        }

        @Override
        public void run() {
            try {
                in = new BufferedReader(new InputStreamReader(
                        sock.getInputStream()));
                out = new PrintWriter(sock.getOutputStream(), true/* auto flush */);
                System.out.println(sock + "접속됨....");
                // 최초 클라이언트에 보내는 메세지
                out.println("사용하실 아이디를 입력하세요.");
                boolean done = false;
                while (!done) {
                    String line = in.readLine();
                    if (line == null)
                        done = true;
                    else
                        routine(line);
                }
            } catch (Exception e) {
                removeClient(this);
                System.err.println(sock + "[" + id + "] 끊어짐.");
                e.printStackTrace();
            }
        }

        public void routine(String line) {
            // CHATALL:오늘은 불타는 금요일.....
            int idx = line.indexOf(':');
            String cmd/* CHATALL */= line.substring(0, idx);
            String data/* 오늘은.. */= line.substring(idx + 1);
            if (cmd.equals(ChatProtocol.ID)) {
                if (data != null && data.length() > 0) {
                    id = data;
                    sendAllClient(ChatProtocol.CHATLIST + ":" + getIds());
                    sendAllClient(ChatProtocol.CHAT + ":" + "[" + id
                            + "]님 입장하였습니다.");
                }
            } else if (cmd.equals(ChatProtocol.CHAT)) {
                // CHAT:bbb;배고프나?
                idx = data.indexOf(';');
                cmd = data.substring(0, idx);// bbb
                data = data.substring(idx + 1);// 배고프나?
                ClientThread ct = findThread(cmd/* bbb */);
                if (ct != null) {
                    ct.sendMessage(ChatProtocol.CHAT + ":" + "[" + id/* aaa */
                            + "] " + data);
                } else {
                    sendMessage(ChatProtocol.CHAT + ":" + "[" + cmd/* bbb */
                            + "] 사용자가 아닙니다.");
                }
            } else if (cmd.equals(ChatProtocol.CHATALL)) {
                sendAllClient(ChatProtocol.CHATALL + ":" + "[" + id/* aaa */
                        + "] " + data);
            } else if (cmd.equals(ChatProtocol.MESSAGE)) {
                // (C->S)MESSAGE:bbb;죽을래?
                // (S->C)MESSAGE:aaa;죽을래?
                idx = data.indexOf(';');
                cmd = data.substring(0, idx);// bbb
                data = data.substring(idx + 1);// 죽을래?
                ClientThread ct = findThread(cmd);
                if (ct != null) {
                    ct.sendMessage(ChatProtocol.MESSAGE + ":" + id/* aaa */
                            + ";" + data);
                } else {
                    sendMessage(ChatProtocol.CHAT + ":" + "[" + cmd/* bbb */
                            + "] 사용자가 아닙니다.");
                }
            }
        }

        // 매개변수로 받은 id로 ClientThread를 찾는다.
        public ClientThread findThread(String id) {
            ClientThread ct = null;
            for (int i = 0; i < vc.size(); i++) {
                ct = vc.get(i);
                if (ct.id.equals(id))
                    break;
            }
            return ct;
        }

        // 접속된 모든 id를 리턴(; 구분) ex)aaa;bbb;홍길동
        public String getIds() {
            String ids = "";
            for (int i = 0; i < vc.size(); i++) {
                ClientThread ct = vc.get(i);
                ids += ct.id + ";";
            }
            return ids;
        }

        public void sendMessage(String msg) {
            out.println(msg);
        }
    }

    public static void main(String[] args) {
        new ChatServer();
    }
}


=========================



package Multi;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dialog;
import java.awt.Frame;
import java.awt.GridLayout;
import java.awt.Label;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.BufferedReader;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.StringTokenizer;
import java.util.Vector;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollBar;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;

public class ChatClient extends JFrame implements ActionListener, Runnable {

    JButton connectBtn, saveBtn, msgBtn, sendBtn;
    JTextField hostTxt, portTxt, msgTxt;
    JTextArea area;
    JList<String> list;
    JScrollPane scroll;
    JScrollBar sb;
    BufferedReader in;
    PrintWriter out;
    Vector<String> vlist;
    boolean flag = false;
    String listTitle = "*******대화자명단*******";
    String id;

    public ChatClient() {
        setTitle("MyChat 2.0");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(470, 500);
        JPanel p1 = new JPanel();
        p1.add(new JLabel("Host", Label.RIGHT));
        p1.add(hostTxt = new JTextField("127.0.0.1", 15));
        p1.add(new JLabel("Port", Label.RIGHT));
        p1.add(portTxt = new JTextField(8008 + "", 8));
        connectBtn = new JButton("connect");
        connectBtn.addActionListener(this);
        p1.add(connectBtn);
        add(BorderLayout.NORTH, p1);
        // //////////////////////////////////////////////////////////////////////////////////////////
        area = new JTextArea("MyChat2.0");
        scroll = new JScrollPane(area,
                JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
                JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
        sb = scroll.getVerticalScrollBar();
        area.setBackground(Color.DARK_GRAY);
        area.setForeground(Color.YELLOW);
        area.setEditable(false);
        add(BorderLayout.CENTER, scroll);
        // /////////////////////////////////////////////////////////////////////////////////////////
        JPanel p2 = new JPanel();
        p2.setLayout(new BorderLayout());
        vlist = new Vector<String>();
        vlist.add(listTitle);
        list = new JList(vlist);
        p2.add(BorderLayout.CENTER, list);
        JPanel p3 = new JPanel();
        p3.setLayout(new GridLayout(1, 2));
        saveBtn = new JButton("Save");
        saveBtn.addActionListener(this);
        msgBtn = new JButton("Message");
        msgBtn.addActionListener(this);
        p3.add(saveBtn);
        p3.add(msgBtn);
        p2.add(BorderLayout.SOUTH, p3);
        add(BorderLayout.EAST, p2);
        // ///////////////////////////////////////////////////////////////////////////////////////////
        JPanel p4 = new JPanel();
        msgTxt = new JTextField("", 33);
        msgTxt.addActionListener(this);
        sendBtn = new JButton("SEND");
        sendBtn.addActionListener(this);
        p4.add(msgTxt);
        p4.add(sendBtn);
        add(BorderLayout.SOUTH, p4);
        setVisible(true);
        setResizable(false);
    }

    public void actionPerformed(ActionEvent e) {
        Object o = e.getSource();
        if (connectBtn/* connect */== o) {
            connect(hostTxt.getText(), Integer.parseInt(portTxt.getText()));
            hostTxt.setEditable(false);
            portTxt.setEditable(false);
            connectBtn.setEnabled(false);
        } else if (saveBtn/* save */== o) {
            String saveStr = area.getText();
            long mills = System.currentTimeMillis();
            try {
                FileWriter fw = new FileWriter("ch25/" + mills + ".txt");
                fw.write(saveStr);
                new SaveMsg(this);
                fw.close();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        } else if (msgBtn/* message */== o) {
            new Message("TO:");
        } else if (sendBtn/* send */== o || msgTxt == o) {
            String msg = msgTxt.getText();
            if (filterMgr(msg)) {
                new Waring(this);
                return;
            }
            if (!flag/* 아이디 입력일때 */) {
                // ID:aaa
                id = msg;
                sendMessage(ChatProtocol.ID + ":" + id);
                setTitle(getTitle() + " - " + id + "님 반갑습니다.");
                area.setText("");
                flag = true;
            } else/* 채팅일때 */{
                int i = list.getSelectedIndex();
                if (i == -1 || i == 0) {// 전체채팅
                    sendMessage(ChatProtocol.CHATALL + ":" + msg);
                } else {
                    String rid = vlist.get(i);
                    sendMessage(ChatProtocol.CHAT + ":" + rid + ";" + msg);
                    area.append("[" + id + "]" + msg + "\n");
                }
            }
        }
        msgTxt.setText("");
        msgTxt.requestFocus();
    }

    public boolean filterMgr(String msg) {// 오늘 밥 머 먹을까?
        boolean flag = false;// false이면 금지어 아님
        String str[] = { "바보", "개새끼", "새끼", "자바", "java", "주호" };
        // 하하 호호 히히
        StringTokenizer st = new StringTokenizer(msg);
        String msgs[] = new String[st.countTokens()];
        for (int i = 0; i < msgs.length; i++) {
            msgs[i] = st.nextToken();
        }
        for (int i = 0; i < str.length; i++) {
            if (flag)
                break;
            for (int j = 0; j < msgs.length; j++) {
                if (str[i].equals(msgs[j])) {
                    flag = true;
                    break;
                }
            }
        }
        return flag;
    }

    public void sendMessage(String msg) {
        out.println(msg);
    }

    public void run() {
        try {
            boolean done = false;
            while (!done) {
                String line = in.readLine();
                if (line == null)
                    done = true;
                else
                    routine(line);
                sb.setValue(sb.getMaximum());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void connect(String host, int port) {
        try {
            Socket sock = new Socket(host, port);
            in = new BufferedReader(
                    new InputStreamReader(sock.getInputStream()));
            out = new PrintWriter(sock.getOutputStream(), true);
            area.setText(in.readLine() + "\n");
        } catch (Exception e) {
            System.err.println("Error in Connect");
            e.printStackTrace();
            System.exit(1);
        }
        new Thread(this).start();
    }

    private void routine(String line) {
        int idx = line.indexOf(':');
        String cmd = line.substring(0, idx);
        String data = line.substring(idx + 1);
        if (cmd.equals(ChatProtocol.CHAT) || cmd.equals(ChatProtocol.CHATALL)) {
            area.append(data + "\n");
        } else if (cmd.equals(ChatProtocol.CHATLIST)) {
            list.removeAll();
            vlist.removeAllElements();
            // "*******대화자명단*******"
            vlist.add(listTitle);
            StringTokenizer st = new StringTokenizer(data, ";");
            while (st.hasMoreTokens()) {
                String s = st.nextToken();
                if (s != null)
                    vlist.add(s);
            }
            list.setListData(vlist);
        } else if (cmd.equals(ChatProtocol.MESSAGE)) {
            idx = data.indexOf(';');
            cmd = data.substring(0, idx);
            data = data.substring(idx + 1);
            new Message("FROM:", cmd, data);
        }
    }

    class SaveMsg extends Dialog implements ActionListener {

        JButton ok;
        ChatClient ct2;

        public SaveMsg(ChatClient ct2) {
            super(ct2, "Save", true);
            this.ct2 = ct2;
            addWindowListener(new WindowAdapter() {
                public void windowClosing(WindowEvent e) {
                    dispose();
                }
            });
            setLayout(new GridLayout(2, 1));
            Label label = new Label("대화내용을 저장하였습니다.", Label.CENTER);
            add(label);
            add(ok = new JButton("확인"));
            ok.addActionListener(this);
            layset();
            setVisible(true);
        }

        public void layset() {
            int x = ct2.getX();
            int y = ct2.getY();
            int w = ct2.getWidth();
            int h = ct2.getHeight();
            int w1 = 150;
            int h1 = 100;
            setBounds(x + w / 2 - w1 / 2, y + h / 2 - h1 / 2, 200, 100);
        }

        public void actionPerformed(ActionEvent e) {
            ct2.area.setText("");
            setVisible(false);
            dispose();
        }
    }

    class Message extends Frame implements ActionListener {

        JButton send, close;
        JTextField name;
        JTextArea msg;
        String mode;// to/from
        String id;

        public Message(String mode) {
            setTitle("쪽지보내기");
            this.mode = mode;
            id = vlist.get(list.getSelectedIndex());
            layset();
        }

        public Message(String mode, String id, String msg) {
            setTitle("쪽지읽기");
            this.mode = mode;
            this.id = id;
            layset();
            this.msg.setText(msg);
            name.setEditable(false);
        }

        public void layset() {
            addWindowListener(new WindowAdapter() {
                public void windowClosing(WindowEvent e) {
                    dispose();
                }
            });
            JPanel p1 = new JPanel();
            p1.add(new Label(mode, Label.CENTER));
            name = new JTextField(id, 20);
            p1.add(name);
            add(BorderLayout.NORTH, p1);
            msg = new JTextArea(10, 30);
            JScrollPane scroll = new JScrollPane(msg,
                    JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
                    JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
            add(scroll);
            JPanel p2 = new JPanel();
            if (mode.equals("TO:")) {
                p2.add(send = new JButton("send"));
                send.addActionListener(this);
            }
            p2.add(close = new JButton("close"));
            close.addActionListener(this);
            add(BorderLayout.SOUTH, p2);
            setBounds(200, 200, 300, 250);
            setVisible(true);
        }

        public void actionPerformed(ActionEvent e) {
            if (e.getSource() == send) {
                sendMessage(ChatProtocol.MESSAGE + ":" + id + ";"
                        + msg.getText());
            }
            setVisible(false);
            dispose();
        }
    }

    class Waring extends Dialog implements ActionListener {
        JButton ok;
        ChatClient ct2;

        public Waring(ChatClient ct2) {
            super(ct2, "경고", true);
            this.ct2 = ct2;
            // ////////////////////////////////////////////////////////////////////////////////////////
            addWindowListener(new WindowAdapter() {
                public void windowClosing(WindowEvent e) {
                    dispose();
                }
            });
            // ///////////////////////////////////////////////////////////////////////////////////////
            setLayout(new GridLayout(2, 1));
            JLabel label = new JLabel("입력하신 글짜는 금지어입니다.", JLabel.CENTER);
            add(label);
            add(ok = new JButton("확인"));
            ok.addActionListener(this);
            layset();
            setVisible(true);
        }

        public void layset() {
            int x = ct2.getX();
            int y = ct2.getY();
            int w = ct2.getWidth();
            int h = ct2.getHeight();
            int w1 = 150;
            int h1 = 100;
            setBounds(x + w / 2 - w1 / 2, y + h / 2 - h1 / 2, 200, 100);
        }

        public void actionPerformed(ActionEvent e) {
            ct2.msgTxt.setText("");
            dispose();
        }
    }

    public static void main(String[] args) {
        new ChatClient();
    }
}






'Java' 카테고리의 다른 글

InputStream / OutputStream 데이터 흐름  (0) 2015.01.02
Chat application using multi thread with vector  (0) 2014.12.30
Socket 통신으로 Image전송  (0) 2014.12.29
KeyListener  (0) 2014.12.28
ArrayList  (0) 2014.12.26
Posted by af334
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

package prac;

import java.awt.image.BufferedImage;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

import javax.imageio.ImageIO;

public class ImageServer {
    public static void main(String[] args){
        ServerSocket ss =null;
        try {
            ss=new ServerSocket(1234);
            Socket socket=ss.accept();
           
            InputStream is =socket.getInputStream();
            BufferedImage bimg=ImageIO.read(is);
            FileOutputStream fout=new FileOutputStream("/img/upload.gif");
            ImageIO.write(bimg, "gif", fout);
           
            fout.close();
       
            System.out.println("서버 :이미지 수신 및 파일에 저장 완료");
           
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

-----------------------------------


package prac;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.OutputStream;
import java.net.Socket;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JLabel;

public class ImageClient {
    public static void main(String[] args){
        JLabel jLabel=new JLabel();
        File imgFile =new File("/img/frame1.gif");
        BufferedImage bufferedImg=null;
       
        try {
            bufferedImg=ImageIO.read(imgFile);
            ImageIcon imgIcon=new ImageIcon(bufferedImg);
            jLabel.setIcon(imgIcon);
           

            uploadingImg(jLabel);    //JLabel에 설정된 이미지를 서버에 업로드 한다
           
        } catch (Exception e) {
                e.printStackTrace();
        }
    }
   


//JLabel에 포함된 ImageIcon데이터를 BufferedImage로 변환하여 서버로 전송한다.

    private static void uploadingImg(JLabel jLabel){
        ImageIcon icon=(ImageIcon)jLabel.getIcon();
        BufferedImage bi=(BufferedImage)icon.getImage();
        Socket socket=null;
       
        try {
            socket=new Socket("localhost",1234);
            OutputStream outStream=socket.getOutputStream();
            ImageIO.write(bi, "gif", outStream);
            outStream.close();
                   
            System.out.println("클라이언트 : 이미 파일 업로드 완료 ");
           
        } catch (Exception e) {
                e.printStackTrace();
        }
    }
}








'Java' 카테고리의 다른 글

Chat application using multi thread with vector  (0) 2014.12.30
Multi Chatting  (0) 2014.12.30
KeyListener  (0) 2014.12.28
ArrayList  (0) 2014.12.26
OutputStream  (0) 2014.12.26
Posted by af334
2014. 12. 28. 05:08
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

implement 했을 때, 오버라이딩하는 메소드들


keyPressed: 키를 눌렀을 때, 키보드의 위치상의 값으로 처리, A와 a가 같다

keyReleased: 키보드에서 손을 땠을 떄의 키보드 위치상의 값 처리. A와 a가 같다

keyTyped : 아스키 코드로 값을 처리해서 a와 A가 다르다. 중봌키 인식이 힘들다. Alt + W 와 같은 복수의 키 인식 불가


package Listener;

import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.JFrame;

class Key extends JFrame implements KeyListener {
    public static void main(String[] args){
        Key kk =new Key();
    }


    public Key() {
        this.setTitle("KeySample");
        this.setDefaultCloseOperation(EXIT_ON_CLOSE);
        this.setBounds(100, 100, 500, 300);
        this.addKeyListener(this);
        this.setVisible(true);
    }

     

    @Override

    public void keyPressed(KeyEvent ke) {
        System.out.println("keyPressed");

    //System.out.println("extendedKey : " + ke.getExtendedKeyCode());

        System.out.println("keyChar : " + ke.getKeyChar());
        System.out.println("keyCode : " + ke.getKeyCode());
        System.out.println("keyLocation : " + ke.getKeyLocation());
    }

    @Override
    public void keyReleased(KeyEvent ke) {
        System.out.println("keyReleased");
    }
   
    @Override
    public void keyTyped(KeyEvent ke) {
        System.out.println("keyTyped");
        }
    }



'Java' 카테고리의 다른 글

Multi Chatting  (0) 2014.12.30
Socket 통신으로 Image전송  (0) 2014.12.29
ArrayList  (0) 2014.12.26
OutputStream  (0) 2014.12.26
InputStream  (0) 2014.12.26
Posted by af334
2014. 12. 26. 08:05
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

컬렉션

1. List

2. Map

3. Set

4. Tree



배열의 단점은 크기가 고정 되어 있다는 것, 그래서 인덱스를 넘어가면 exception이 발생한다.

하지만 list는 들어오는 데이터에 따라 알아서 공간을 늘려주기 때문에 더 효율적이다


List

- 배열 구조를 가지고 있다.

- 중복 값을 허용한다.

- 순서가 있다.


List에서도 가장 많이 쓰는 ArrayList

1. 데이터를 차례대로 입력할 때 쓰이는 자료구조 클래스

2. 인덱스가 있다.

3. 데이터가 중복 될 수 있다.

4. 제네릭 문법을 사용  =>     <자료형> (jdk 1.5.부터 적용)

5. ArrayList와 LinkedList는 List의 대표 클래스







package ArrayList;

import java.util.ArrayList;

public class ArrayListEx {
    public static void main(String[] args){
        ArrayList<String>    list =new ArrayList<String>();
       
        list.add("안녕하세요");
        list.add("반가워요");
        list.add("영어공부 어떻게 해요");
        list.add("저는 미드 많이 봐요");
       
        System.out.println("리스트 사이즈 : " + list.size());
        System.out.println("첫번쨰 값 : "+ list.get(0));
       
        System.out.println("첫째값 지우기 ");
        list.remove(0);
        System.out.println("지운 후 리스트 사이즈 : " + list.size());
        System.out.println("지운 후 첫번째 값 : " + list.get(0));
       
        System.out.println("리스트 클리어 ");
        list.clear();
        System.out.println("클리어 후 리스트 사이즈 " + list.size());
    }
}

'Java' 카테고리의 다른 글

Socket 통신으로 Image전송  (0) 2014.12.29
KeyListener  (0) 2014.12.28
OutputStream  (0) 2014.12.26
InputStream  (0) 2014.12.26
DataInputStream / DataOutputStream  (0) 2014.12.25
Posted by af334
2014. 12. 26. 03:04
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

package prac;

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.border.Border;
import javax.swing.border.EtchedBorder;
import javax.xml.stream.events.StartDocument;

public class ChatClient {
    final static String SERVER_ADDR="localhost";
    final static int SERVER_PORT=8010;
    static Socket socket;
    static volatile BufferedReader br;
    static PrintWriter pw;
    static JButton btnSend;
    static JPanel createGUI(){
        JPanel pnlLayout=new JPanel();
        pnlLayout.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
        pnlLayout.setLayout(new BorderLayout());
        JPanel pnlLeft =new JPanel();
        pnlLeft.setLayout(new BorderLayout());
        final JTextField txtUserName=new JTextField(30);
        pnlLeft.add(txtUserName, BorderLayout.NORTH);
        final JTextArea txtInput =new JTextArea(5,30);
        txtInput.setEnabled(false);
        pnlLeft.add(new JScrollPane(txtInput), BorderLayout.CENTER);
        final JTextArea txtOutput =new JTextArea(10,30);
        txtOutput.setFocusable(false);
        pnlLayout.add(new JScrollPane(txtOutput), BorderLayout.SOUTH);
        pnlLayout.add(pnlLeft,BorderLayout.WEST);
        JPanel pnlRight =new JPanel();
        pnlRight.setLayout(new BorderLayout());
        final JTextArea txtUsers=new JTextArea(10,10);
        txtUsers.setFocusable(false);
        Border border=BorderFactory.createEtchedBorder(EtchedBorder.LOWERED);
        txtUsers.setBorder(border);
        pnlRight.add(txtUsers, BorderLayout.NORTH);
        JPanel pnlButtons=new JPanel();
        pnlButtons.setLayout(new GridLayout(3,1));
        final JButton btnConnect =new JButton("Connect");
        ActionListener al;
        al=new ActionListener() {
           
            @Override
            public void actionPerformed(ActionEvent ae) {
                txtUserName.setFocusable(false);
                String username=txtUserName.getText().trim();
                try {
                    socket=new Socket(SERVER_ADDR, SERVER_PORT);
                    btnConnect.setEnabled(false);
                    InputStreamReader isr;
                    isr=new InputStreamReader(socket.getInputStream());
                    br=new BufferedReader(isr);
                    pw=new PrintWriter(socket.getOutputStream(), true);
                    txtOutput.append(br.readLine()+ "\n");
                    pw.println((!username.equals(""))?username:"unknown");
                    txtInput.setEnabled(true);
                    btnSend.setEnabled(true);
                    new Thread(new Runnable() {
                       
                        @Override
                        public void run() {
                            String line;
                            try {
                                while ((line=br.readLine())!=null) {
                                    if (line.charAt(0)!='!'){
                                        txtOutput.append(line+"\n");
                                        continue;
                                    }
                                    txtUsers.setText("");
                                    String[] users;
                                    users=line.substring(1).split(" ");
                                    for (String user : users) {
                                        txtUsers.append(user);
                                        txtUsers.append("\n");
                                    }
                                }
                            } catch (IOException ioe) {
                                txtOutput.append("lost the link");
                                return;
                            }
                        }
                    }).start();
                   
                } catch (Exception e) {
                    txtOutput.append("unable to connect to server");
                }
            }
        };
       
        btnConnect.addActionListener(al);
        pnlButtons.add(btnConnect);
        btnSend=new JButton("Send");
        btnSend.setEnabled(false);
        al=new ActionListener() {
           
            @Override
            public void actionPerformed(ActionEvent ae) {
                pw.println(txtInput.getText());
                txtInput.setText("");
            }
        };
        btnSend.addActionListener(al);
        pnlButtons.add(btnSend);
        JButton btnQuit=new JButton("Quit");
        al=new ActionListener() {
           
            @Override
            public void actionPerformed(ActionEvent ae) {
                try {
                    if(socket!=null)
                        socket.close();
                   
                } catch (IOException ioe) {
                }
                System.exit(0);
            }
        };
        btnQuit.addActionListener(al);
        pnlButtons.add(btnQuit);
        pnlRight.add(pnlButtons, BorderLayout.SOUTH);
        pnlLayout.add(pnlRight, BorderLayout.EAST);
        return pnlLayout;
    };
   
    public static void main(String[] args){
        Runnable r =new Runnable() {
           
            @Override
            public void run() {
                JFrame f =new JFrame("ChatClient");
                f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                f.setContentPane(createGUI());
                f.pack();
                f.setResizable(false);
                f.setVisible(true);
            }
        };
        EventQueue.invokeLater(r);
    }
}








'Java > Working-level Java' 카테고리의 다른 글

Thread 2  (0) 2015.01.14
Thread  (0) 2015.01.06
System  (0) 2015.01.06
StringBuffer / StringBuilder  (0) 2015.01.03
ChatServer  (0) 2014.12.24
Posted by af334
2014. 12. 26. 01:24
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

OutputStream 클래스에서 파생된 클래스들


FileOutputSream

ObjectOutputStream

FilterOutputStream

ByteOutputStream


1byte씩 표현된다

데이터를 쓸 때는 기본적으로 write()메소드를 쓴다.


write()메소드는 여러가지로 나눌 수 있다.


write(int)  : 한 바이트에 해당하는 데이터를 기록할 때 사용한다.

write(Byte[])  : byte[] 안에 있는 데이터를 한번에 기록해 준다.

write(Byte[], int, int)  :  byte안에 있는 데이터를 원하는 위치에 숫자만큼 데이터를 기록해 준다.





package readerData;

import java.io.FileOutputStream;
import java.io.OutputStream;

public class outPutSt {
    public static void main(String[] args){


// 파일이 존재하면 덮어쓰고, 존재하지 않으면 새로 생성한다.

        try {
            OutputStream out=new FileOutputStream("end.txt");
            String str="다시 이 문자열을 파일에 기록하도록 하자 ";
            byte[] arr=str.getBytes();
           
            out.write(arr);     // 바이트 배열에 문자열을 기록한다
            out.close();
           
        } catch (Exception e) {
            System.out.println("파일 전송 실패");
        }
        System.out.println("파일 저장 완료");
    }
}





'Java' 카테고리의 다른 글

KeyListener  (0) 2014.12.28
ArrayList  (0) 2014.12.26
InputStream  (0) 2014.12.26
DataInputStream / DataOutputStream  (0) 2014.12.25
Finding IP using the domain name  (0) 2014.12.25
Posted by af334
2014. 12. 26. 01:12
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

InputStream 클래스에서 파생된 클래스


FileInputStream

ZipInputStream

DataInputStream

BufferedInputStream


각 클래스에서 데이터를 읽을 때는 기본적으로 read()메소드를 사용해 1byte씩 데이터를 읽는다






package readerData;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

public class InputSt {
    public static void main(String[] args) throws IOException{
       
        InputStream in =new FileInputStream("endend.txt");
       
        while (true) {
            int data=in.read();    // read()는 1byte씩 가져온다
            System.out.println(data);
           
            if (data==-1) {     // 파일의 끝이면 -1을 반환 한다
                break;
            }
        }
    }
}


FileInputStream() 파라미터로 파일의 주소를 넣어 주면 된다. 상대경로를 이용하려면 현재 프로젝트폴더에 파일이 있어야 한다.

다른 위치의 파일을 읽어오고 싶으면 절대경로를 넣어주면 된다.


주의할 점은 FileInputStream은 한글을 제대로 인식을 못한다. 그래서 한글로 된 파일을 읽어오면 알 수 없는 형태의 글자로 표시가 된다.

버퍼를 이용하는 방법도 있지만 Scanner클래스를 이용해서 한글 파일을 읽어 올 수도 있다.



---------------------------------------



Scanner 클래스를 이용해 파일읽기



package readerData;

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Scanner;

public class scanInput {
    public static void main(String[] args){
        InputStream in=null;
       
        try {
            in =new FileInputStream("endend.txt");
           
            Scanner s=new Scanner(in);           

    // Scanner 클래스의 파라미터로 객체 생성된 in 을 넘겨준다.


            while (s.hasNext()) {
                String str=s.nextLine();     // 한줄 씩 읽어온다
                System.out.println(str);
            }
        } catch (Exception e) {
            System.out.println(e);
        }
    }
}







'Java' 카테고리의 다른 글

ArrayList  (0) 2014.12.26
OutputStream  (0) 2014.12.26
DataInputStream / DataOutputStream  (0) 2014.12.25
Finding IP using the domain name  (0) 2014.12.25
Multi Chatting  (0) 2014.12.25
Posted by af334
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

InputStream  >>> DataInputStream

OutputStream >>> DataOutputStream


바이트 단위가 아닌 8가지의 기본 자료형의 단위로 읽고 쓸 수 있다는 장점이 있다.




package readerDate;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class readerDate {
    public static void main(String[] args) throws IOException{
        String fileUrl="testtest.txt";
        OutputStream out=new FileOutputStream(fileUrl);
        InputStream in =new FileInputStream(fileUrl);
        DataOutputStream dos=new DataOutputStream(out);
        DataInputStream dis=new DataInputStream(in);
       
        try {
            String outData="안녕하세요 저의 블로그입니다";
            dos.writeUTF(outData);
            System.out.println("파일 생성 완료 ");
        } catch (Exception e) {
            System.out.println("파일 생성 실패");
        }
       
        System.out.println(fileUrl + "을 읽어 옵니다");
       
       
        try {
            String inData=dis.readUTF();
            System.out.println(inData);
            dis.close();
            in.close();
           
        } catch (Exception e) {
            System.out.println("파일 읽기 실패 ");
        }
    }
}


------------------------------------------------------------------------------



DataInputStream 클래스


DataInputStream(InputStream in)        DataInputStream 객체를 생성한다.


각 자료형에 맞는 데이터를 읽어온다.

boolean readBoolean()

byte readByte()

char readChar()

short readShort()

int readInt()

long readLong()

float readFloat()

double readDouble()


String readUTF()     UTF형식으로 쓰여진 문자를 읽는다. 더이상 데이터가 없으면 EOFException을 발생 시킨다.



--------------------


DataOutputStream 클래스


DataOutputStream(OutputStream out)    DataoutStream    객체를 생성한다.


각 자료형에 알맞는 데이터를 출력한다.

void writeBoolean(boolean b)

void writeByte(byte b)

void writeChar(char c)

void writeShort(short s)

void writeInt (int i)

void writeLong(long l)

void writeFloat(float f)

void writeDouble(double d)


void writeUTF(String s)     UTF형식의 문자를 출력한다

void writeChars(String s)     주어진 문자열을 출력한다.







'Java' 카테고리의 다른 글

OutputStream  (0) 2014.12.26
InputStream  (0) 2014.12.26
Finding IP using the domain name  (0) 2014.12.25
Multi Chatting  (0) 2014.12.25
class StringBuilder  (0) 2014.12.24
Posted by af334
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

package InetAddress;

import java.net.InetAddress;
import java.net.UnknownHostException;

public class Inetaddress {
    public static void main(String[] args)throws UnknownHostException{
        String host="www.naver.com";
        InetAddress inet=InetAddress.getByName(host);
                // (IP주소를 표현한 클래스) 클래스는 static이므로 객체 생성없이 바로 접근한다.   
        String ip=inet.getHostAddress();
       
        System.out.println("IP : " + ip);
       

//만약 여러개의 IP를 사용할 경우

        InetAddress[] ips=InetAddress.getAllByName(host);
        System.out.println("------------------------------------------");
        for(InetAddress n : ips){http://inchoryang.tistory.com/admin/entry/post
            System.out.println(n.getHostAddress());
           
        }
    }
}

'Java' 카테고리의 다른 글

InputStream  (0) 2014.12.26
DataInputStream / DataOutputStream  (0) 2014.12.25
Multi Chatting  (0) 2014.12.25
class StringBuilder  (0) 2014.12.24
Runtime.getRuntime().exec()  (0) 2014.12.24
Posted by af334
2014. 12. 25. 06:03
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

BroadCastingServer.java



package prac;

import java.awt.Frame;
import java.awt.TextArea;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

//클라이언트의 접속을 받아 모든 클라이언트에게 데이터르 전송시키는 serverThread객체를 생성
public class BroadCastingServer {


    //서버의 폼을 구성하는 Component

    private Frame f;
    private TextArea state;

  

    //클라이언트와 소켓을 형성하기 위한 클라스 선언

    private ServerSocket server;
    private Socket socket;


    //데이터를 주고 받을 수 있도록 Thread로 구현한 클래스 선언    

    private serverThread st;
   
    // 생성자, GUI폼 구성
    public BroadCastingServer(){
        f=new Frame("Server");
       
        state=new TextArea("",30,50,TextArea.SCROLLBARS_NONE);
        state.setEditable(false);
       
        f.add(state,"Center");
        f.setSize(300, 400);
        f.setLocation(300, 300);
        f.setResizable(false);
        f.setVisible(true);
       
        f.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e){
                System.exit(0);
            }
        });
    } // 생성자 end


   // 서버를 실행시키는 메소드    

    public void startServer(){
        try {

    //대표 포트 6666을 가지고 클라이언트의 접속을 기다리는 ServerSocket 객체 생성

            server=new ServerSocket(6666);
           
            while (true) {

//클라이언트와 접속을 성공시켜 소켓 생성

                socket=server.accept();


//스트림 생성

                DataInputStream dis=new DataInputStream(socket.getInputStream());
                DataOutputStream dos=new DataOutputStream(socket.getOutputStream());
               

//클라이언트가 전송하는 ID값을 받아들임

                String name =dis.readUTF();
               

//broadcasting을 해주는 serverThread객체 생성

                st=new serverThread(socket, state, dis, dos, name); 
                Thread t=new Thread(st);
                t.start();
            }// while end
           
           
        } catch (IOException ioe) {
            System.out.println(ioe.getMessage());
        }
    }   //startServer(0 end

    public static void main(String[] args){
        BroadCastingServer ser =new BroadCastingServer();
        ser.startServer();
    }
   
}

--------------------------------------------------------------------------


serverThread.java




package prac;

import java.awt.TextArea;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.util.Enumeration;
import java.util.StringTokenizer;
import java.util.Vector;


//Thread를 이용해 모든 클라이언트에게 데이터를 전송해주는 broadcasting을 구현한 클래스
public class serverThread implements Runnable{


    // 접속한 클라이언트를 저장하는 vector 객체 생성
    private static Vector list =new Vector();
   

    // BroadCastingServer가 넘겨주는 argument를 저장하기 위한 멤버 변수 선언  

    private Socket socket;
    private TextArea state;
    private DataInputStream dis;
    private DataOutputStream dos;
   

    // 사용자의 대화명을 저장하는 변수 선언

    String talkName;
   

    //생성자

   // BroadCastingServer에서 넘겨주는 argument를 멤버변수에 할당

    public serverThread(Socket socket, TextArea state, DataInputStream dis, DataOutputStream dos, String talkName) throws IOException{
        this.socket=socket;
        this.state=state;
        this.dis=dis;
        this.dos=dos;
        this.talkName=talkName;
       
    }
   
   
    @Override
    public void run() {

// 서버의 TextArea에 현재 접속한 클라이언트를 출력

        state.append(talkName + " 님이 입장하셨습니다\n");
       

// 모든 클라이언트들에게 현재 접속한 사용자를 알려줌

        compareState("LogOut/" + talkName + "님이 입장하셨습니다");
       
        try {

    // 현재 접속한 사용자를 Vector에 추가

            list.addElement(this);
            while (true) {
                String msg=dis.readUTF();
                compareState(msg);
            }    // while end
        } catch (IOException ioe) {

                // 소켓이 끊어지거나, 스트림이 해체 되었을 경우

// exception이 발생한 경우는 퇴장한 경우이므로

                state.append(talkName + "님이 퇴장 하였습니다.\n");
                compareState("LogOut/" + talkName + "님이 퇴장 하였습니다.\n");
               

// Vector 에서 현재 Exception이 난 Object를 제거

                list.removeElement(this);
                try {
                    socket.close();
                } catch (Exception e) {
                    System.out.println("소켓 닫는 도중 에러 발생 ");
                }   
        } // catch end
    }   //run() end

   

   // 현재 Login 을 하려고 하는 건지, 대화 내용을 보내는 중인지를 판단하기 위해서 선언한 method

    public void compareState(String message){
        StringTokenizer st =new StringTokenizer(message,"/");
        String protocol=st.nextToken();    //Login, Logout Message
        String msg=st.nextToken();
        System.out.println(msg);
               
        if(protocol.equals("Login")|| protocol.equals("LogOut")){
            broadCasting("NONE",msg);
        }else{
            broadCasting(talkName, msg);
        }
    }    //compareState() end

// 현재서버에 접속한 모든 클라이언트에게 메세지를 보내주는 method

//BroadCasting  기능이 먼저 완료되어 채팅글이 꼬이지 않도록 한다.

    public void broadCasting (String talkName, String message){
        synchronized (list) {
            Enumeration e =list.elements();
           
            while(e.hasMoreElements()){
                serverThread temp=(serverThread)e.nextElement();
                try {
                    temp.dos.writeUTF(talkName);
                    temp.dos.writeUTF(message);
                } catch (IOException ioe) {
                    System.out.println(ioe);
                }
            }  // while end
        }   //synchronized() end
    }   //broadCasting
}


-------------------------------------------------------------------------------------


BroadCastingClient.java





package prac;

import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.Frame;
import java.awt.GridLayout;
import java.awt.Label;
import java.awt.Panel;
import java.awt.TextArea;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;

public class BroadCastingClient implements Runnable, ActionListener{
    // 클라이언트의 폼을 구성하는 component
    Frame first, second;
    Panel p;
    TextField ipField;
    TextField idField;
    Button connection;
    TextArea talkScreen;
    TextField tf;
   

    // 서버와의 접속을 위한 socket 객체 선언

    Socket socket;
   

    // 스트림 클래스 선언

    DataInputStream dis;
    DataOutputStream dos;
    Thread listen;
   

    // 생성자, 클라이언트 GUI폼을 구성     

    public BroadCastingClient(){
        first=new Frame("LOGIN");


// second=new Frame("접속 성공");

        connection =new Button("Connect");
       

// Server 의 IP와 대화명을 받아들이는 TextField를 생성

        ipField=new TextField(15);
        idField=new TextField(15);
       

// Label을 붙인 Panel

        Panel p1=new Panel();
        p1.setLayout(new GridLayout(2,1,0,10));
        p1.add(new Label("Server", Label.CENTER));
        p1.add(new Label("ID",Label.CENTER));
       

// TextField를 붙인 Panel

        Panel p2=new Panel();
        p2.setLayout(new GridLayout(2,1,0,10));
        p2.add(ipField);
        p2.add(idField);
       
        Panel p3=new Panel();
        p3.add(p1);
        p3.add(p2);
       

// 연결 시도 프레임 구성

        first.setLayout(new BorderLayout(0,10));
        first.add(p3,"Center");
        first.add(connection, "South");
       

// Window의 종료 이벤트 처리

        first.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e){
                System.exit(0);
            }
        });

        first.setSize(300, 150);
        first.setLocation(300, 300);
        first.setVisible(true);


        // 버튼에 ActionEvent를 등록 시킴
        connection.addActionListener(this);
    }   // 생성자 end
   
    // 로그인 프레임이 종료한 후에 대화를 나눌 수 있는 GUI폼을 구성해 주는 메소드
    public void secondFrame(String id){
        second=new Frame(id+ " : Client");
        tf=new TextField(15);
       
        talkScreen = new TextArea("",30,50,TextArea.SCROLLBARS_NONE);
        talkScreen.setEditable(false);
       
        second.add("Center", talkScreen);
        second.add("South", tf);
        second.setSize(320, 420);
        second.setVisible(true);
       

// Window의 종료 이벤트 처리

        second.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e){
                System.exit(0);
            }
        });
        tf.addActionListener(this);
    }   // secondFrame() end
   

    //  Server 와의 연결을 시도하는 메소드

    public void connectServer(String id,String address, int port){
        try {

    // 서버와의 연결

            socket=new Socket(address,port);
           

    // 현재 접속한 서버와 스트림 형성

            dis =new DataInputStream(socket.getInputStream());
            dos=new DataOutputStream(socket.getOutputStream());
            dos.writeUTF(id);
        } catch (IOException ioe) {
             System.out.println("서버가 없습니다");
             System.exit(0);
        }

// 클라이언트 자체도 Thread구동 시킴

        listen=new Thread(this);
        listen.start();   // run() 메소드 호출
    }   // connectServer() end
   
    
    @Override

    // 텍스트 필드에서 데이터를 입력하고, 엔터를 치는 ActionEvent 처리
    public void actionPerformed(ActionEvent av) {

// TextField에서 Event가 발생 했을 경우 (TextField에 값 입력 후 엔터키)

        if(av.getSource()==tf){   // 두번째 화면
            try {

// 서버측으로 데이터 전송

                dos.writeUTF("Message/" +tf.getText());
                tf.setText(" ");
               
            } catch (IOException ioe) {
                    System.out.println(ioe);
            }
           

// Button에서 Event가 발생 했을 경우 (Button 클릭)

        }else if(av.getSource()==connection){
            String address=ipField.getText();
            String id=idField.getText();
           
            first.setVisible(false);
            first.dispose();
           
            secondFrame(id);
            connectServer(id, address, 6666);
        }
    }

    @Override
    public void run() {

// 서버로부터 받은 데이터를 자신의 TextArea에 출력 시킴

        try {
            while (true) {    // serverThread.java 파일 99,100 라인
                String id=dis.readUTF();   //대화명(talkName)을 읽음
                String line = dis.readUTF();   // message를 읽음
               
                if(id.equals("NONE")){    // 입장과 퇴장
                    talkScreen.append(line +"\n");
                   
                }else{
                    talkScreen.append("["+id+"]:"+line+"\n");
                }
            }
           
        } catch (IOException ioe) {
                talkScreen.append("서버에서 데이터를 읽는 중 에러 발생");
                try {
                    Thread.sleep(1000);    // 1초동안 block상태로 만듬
                } catch (InterruptedException e) {

                }
                System.exit(0);
        }
    }  // catch end

    public static void main(String[] args){
        BroadCastingClient bcc=new BroadCastingClient();
    }
}
 












'Java' 카테고리의 다른 글

DataInputStream / DataOutputStream  (0) 2014.12.25
Finding IP using the domain name  (0) 2014.12.25
class StringBuilder  (0) 2014.12.24
Runtime.getRuntime().exec()  (0) 2014.12.24
open web browser  (0) 2014.12.23
Posted by af334
이전버튼 1 ··· 5 6 7 8 9 이전버튼