**채팅 클라이언트 프로그램을 만들기 위해서 우선 Frame 을 만들어 준다.
여기서 중요 한포인트는 멤버로 BufferedWriter 를 선언해주고 setter를 만든다. 이유는 메인함수에서 연결되있는 socket에 접근하기 위해서 이다.
public class ChatClientFrame extends JFrame implements ActionListener{
private JPanel inputPanel;
private JTextField inputTF;
private JButton inputBtn;
private JTextArea chatArea;
private BufferedWriter bw;
private JScrollPane jsp;
public void setBw(BufferedWriter bw) {
this.bw = bw;
}
public JTextArea getChatArea() {
return chatArea;
}
public ChatClientFrame(JTextArea chatArea){
this.chatArea = chatArea;
}
public ChatClientFrame(){
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setTitle("채팅입니다");
inputPanel = new JPanel();
inputTF = new JTextField(25);
inputBtn = new JButton("전송");
chatArea = new JTextArea(20,30);
//컴포넌트 속성 세팅
chatArea.setEditable(false);
inputTF.addActionListener(this);
inputBtn.addActionListener(this);
jsp = new JScrollPane(chatArea);
inputPanel.add(inputTF);
inputPanel.add(inputBtn);
this.add(jsp, BorderLayout.CENTER);
this.add(inputPanel, BorderLayout.SOUTH);
this.pack();
this.setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == inputBtn || e.getSource() == inputTF)
{
String msg = inputTF.getText();
try {
// 메인함수에서 연결된 socket의 BUfferedWriter에 write
bw.write(msg + "\n");
bw.flush();
} catch (IOException e1) {
// FIXME Auto-generated catch block
e1.printStackTrace();
}
if(msg.equals(""))
{
return;
}
chatArea.append("나 : " + msg + "\n");
inputTF.setText("");
inputTF.requestFocus();
}
}
}
** 마지막으로 클라이언트 메인함수를 작성해 봅시다.
public class TCP_ChatClient {
public static void main(String[] args) {
Socket socket = null;
ChatClientFrame ccf = new ChatClientFrame(); //ChatClientFrame 클래스 객체를 만들어준다.
try {
socket = new Socket(InetAddress.getByName("70.12.115.106"), 5000);
Thread t = new Thread(new Receiver(socket, ccf));
ccf.setBw(new BufferedWriter
(new OutputStreamWriter(socket.getOutputStream())));
t.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
→10월 7일 네트워크 프로그래밍 TCP (단체 채팅 서버코드 예제)
'[JAVA]' 카테고리의 다른 글
[JAVA]10월 14일 스윙 컴포넌트, TextArea 를 활용한 예제.(KeyListner) (0) | 2015.10.14 |
---|---|
[JAVA]10월 14일 스윙 컴포넌트, ImageIcon 으로 Button과 Label에 사진입히기 (0) | 2015.10.14 |
[JAVA]10월 13일 배치 관리자 FlowLayout, BorderLayout, GridLayout (0) | 2015.10.13 |
[JAVA]10월 13일 이벤트 처리 Action, Key, Mouse, MouseMotion (0) | 2015.10.13 |
[JAVA]10월 12일 이벤트 처리 (0) | 2015.10.12 |