1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119
| import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.net.*; import java.io.*;
public class ChatClient extends JFrame implements ActionListener, Runnable { JTextArea output; JTextField input; JButton send; Socket socket; BufferedReader br; PrintWriter pw; Thread t;
public void init() { output = new JTextArea(); input = new JTextField(); send = new JButton("보내기"); JPanel p = new JPanel();
JScrollPane pane = new JScrollPane(output); getContentPane().add("Center", pane); output.setEditable(false);
p.setLayout(new BorderLayout()); p.add("Center", input); p.add("East", send);
this.add("South", p);
setBounds(400, 80, 300, 300); setTitle("채팅창"); setVisible(true);
this.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { pw.println("quit"); pw.flush(); try { br.close(); pw.close(); socket.close(); } catch (IOException io) { io.printStackTrace(); }
System.exit(0); } }); input.addActionListener(this); send.addActionListener(this);
String serverIP = JOptionPane.showInputDialog(this, "서버의 IP를 입력하세요", "서버IP", JOptionPane.QUESTION_MESSAGE); if (serverIP == null || serverIP.equals("")) System.exit(0); String name = JOptionPane.showInputDialog(this, "대화명을 입력하세요", "대화명", JOptionPane.QUESTION_MESSAGE); if (name == null || name.equals("")) name = "방문자"; try { socket = new Socket(serverIP, 9500);
br = new BufferedReader(new InputStreamReader( socket.getInputStream())); pw = new PrintWriter(new OutputStreamWriter( socket.getOutputStream()));
pw.println(name); pw.flush(); t = new Thread(this); t.start(); } catch (UnknownHostException e) { System.out.println("소캣생성시 error : " + e.toString()); } catch (IOException io) { System.out.println("소캣생성시 IO error : " + io.toString()); } }
public void actionPerformed(ActionEvent e) { String data = input.getText(); pw.println(data); pw.flush(); input.setText(""); }
public void run() { String data = null; while (true) { try { data = br.readLine(); if (data == null || data.toLowerCase().equals("quit")) { br.close(); pw.close(); socket.close(); System.exit(0); } } catch (IOException io) { io.printStackTrace(); }
output.append(data + "\n");
int position = output.getText().length(); output.setCaretPosition(position); } }
public static void main(String[] args) { new ChatClient().init(); } }
|