아래 코드는 Head first Java의 예제이다.
import java.io.*;
import java.net.*;
import java.util.*;
import javax.swing.*;
import com.sun.corba.se.spi.servicecontext.SendingContextServiceContext;
import java.awt.*;
import java.awt.event.*;
public class SimpleChatclient {
JTextArea incoming;
JTextField outgoing;
BufferedReader reader;
PrintWriter writer;
Socket sock;
public static void main(String[] args){
SimpleChatclient client = new SimpleChatclient();
client.go();
}
public void go(){
JFrame frame = new JFrame("Simple Chat Client");
JPanel mainPanel = new JPanel();
incoming = new JTextArea(15,50);
incoming.setLineWrap(true);
incoming.setWrapStyleWord(true);
incoming.setEditable(false);
JScrollPane qScroller = new JScrollPane(incoming);
qScroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
qScroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
outgoing = new JTextField(20);
JButton sendButton = new JButton("Send");
sendButton.addActionListener(new SendButtonListener());
mainPanel.add(qScroller);
mainPanel.add(outgoing);
mainPanel.add(sendButton);
setUpNetworking();
Thread readerThread = new Thread(new IncomingReader());
readerThread.start();
frame.getContentPane().add(BorderLayout.CENTER, mainPanel);
frame.setSize(400, 500);
frame.setVisible(true);
}
private void setUpNetworking(){
try{
sock = new Socket("127.0.0.1",5000);
InputStreamReader streamReader = new InputStreamReader(sock.getInputStream());
reader = new BufferedReader(streamReader);
writer = new PrintWriter(sock.getOutputStream());
System.out.println("networking established");
}catch(IOException ex){
ex.printStackTrace();
}
}
public class SendButtonListener implements ActionListener{
public void actionPerformed(ActionEvent ev){
try{
writer.println(outgoing.getText());
writer.flush();
}catch(Exception ex){
ex.printStackTrace();
}
outgoing.setText("");
outgoing.requestFocus();
}
}
public class IncomingReader implements Runnable{
public void run(){
String message;
try{
while((message = reader.readLine())!= null){
System.out.println("read "+ message);
incoming.append(message+ "\n");
}
}catch(Exception ex){
ex.printStackTrace();
}
}
}
}
'개발 이야기 > 유용한 Coding' 카테고리의 다른 글
ANT FTP 에러 해결하는 방법 (1) | 2008.07.28 |
---|---|
chat Server (0) | 2008.05.14 |
자바관련 잡다한 이야기 - 스레드의 동기화 문제 (1) | 2008.05.14 |
자바관련 잡다한 이야기 - 네트워크와 스레드 (0) | 2008.05.13 |
자바관련 잡다한 이야기 - 인터페이스와 다형성 (0) | 2008.05.13 |