¼ÒÄÏÀ» ÀÌ¿ëÇØ °£´ÜÈ÷ ±¸ÇöÇÑ Ã¤ÆÃ ¿¹Á¦
ChatClient.java
import java.io.*;
import java.net.*;
import java.util.*;
import java.awt.*;
import java.awt.event.*;
public class ChatClient extends Panel {
private TextField tfMessage = new TextField();
private TextArea taContent = new TextArea("Jabook Chatting! (³ª°¡½Ã·Á¸é 'exit'¸¦ ÃÄÁÖ¼¼¿ä)", 30, 50);
private Socket client = null;
private BufferedReader br = null;
private BufferedWriter bw = null;
public ChatClient(String ip, int port, String id) throws IOException {
this.setLayout(new BorderLayout());
this.add("Center", taContent);
this.add("South", tfMessage);
taContent.setEditable(false);
tfMessage.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
tfMessage_actionPerformed(e);
}
});
try {
client = new Socket(ip, port);
br = new BufferedReader(new InputStreamReader(client.getInputStream()));
bw = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));
bw.write(id);
bw.newLine();
bw.flush();
} catch (IOException e) {
System.out.println("Á¢¼Ó ½ÇÆÐ!!");
throw e;
}
SendMessage sm = new SendMessage(br, this);
sm.start();
}
public void tfMessage_actionPerformed(ActionEvent e) {
String msg = tfMessage.getText().trim();
if (!msg.equals("")) {
try {
if (msg.equalsIgnoreCase("exit"))
System.exit(0);
bw.write(msg);
bw.newLine();
bw.flush();
tfMessage.setText("");
} catch (IOException ex) {}
}
}
public void message(String msg) {
taContent.append("\n"+msg);
tfMessage.requestFocus();
}
public static void main(String[] args) {
int port = 5000;
String ip = args[0];
String id = args[1];
Frame f = new Frame("Chat Client");
try {
f.add(new ChatClient(ip, port, id), BorderLayout.CENTER);
} catch (IOException e) {
System.exit(-1);
}
f.pack();
f.setVisible(true);
}
class SendMessage extends Thread {
BufferedReader br = null;
ChatClient cc = null;
public SendMessage(BufferedReader br, ChatClient cc) {
this.cc = cc;
this.br = br;
}
public void run() {
String msg = "";
while (true) {
try {
msg = br.readLine();
if (msg != null) {
cc.message(msg);
}
} catch (IOException e) {
}
}
}
}
}
C:\javaExample\17>javac ChatClient.java
C:\javaExample\17>java ChatClient localhost Jabook
Ŭ¶óÀÌ¾ðÆ® ÇÁ·Î±×·¥À» ½ÇÇà½Ã۰í ÇÁ·¹ÀÓÀÌ ¶ß¸é ÅØ½ºÆ® Çʵ忡 ¿øÇÏ´Â ¹®ÀåÀ» ÀÔ·ÂÇÏ¸é µÈ´Ù.
jabookÀúÀÚ¸íÇÔ |
Á¦¸ñ:¼Ò¼³°°Àº¹Ì´ÏÄÚµå ÀÛ¼ºÀÚ:Àںϸâ¹ö ±è¿Ï±â |