본문 바로가기

[JAVA]

[JAVA]10월 13일 GUI_Chat_Client, GUI_채팅 클라이언트 코드 예제

**채팅 클라이언트 프로그램을 만들기 위해서 우선 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();

}

}

}


**그다음 읽어서 ChatArea 에 띄어줄 Receiver 클래스를 작성해 봅시다.
여기서 중요한것은 아래 있는 private JTextArea ta; 얘가 ChatClientFrame 에 있는 JTextArea chatArea; 에 접근 해야 한다. 그래서 생성자에 다음과 같은 방법으로 ChatClientFrame 에 있는 JTextArea chatArea; 에 접근했다.

public class Receiver implements Runnable{
private Socket socket;
private JTextArea ta;
public Receiver(Socket socket, ChatClientFrame ccf)
{
this.socket = socket;
this.ta = ccf.getChatArea();
}
@Override
public void run() {
// FIXME Auto-generated method stub
try {
BufferedReader br = new BufferedReader
(new InputStreamReader(socket.getInputStream()));
String msg = null;
while((msg = br.readLine()) != null)
{
if(msg.equals("종료"))
{
break;
}
ta.append(socket.getInetAddress() + ":" + msg + "\n");
}
catch (IOException e) {
System.out.println("문제 발생 프로그램을 종료합니다.");
}
finally
{
if(socket != null)
try {
socket.close();
} catch (IOException e) {
// FIXME Auto-generated catch block
e.printStackTrace();
}
System.exit(1);
}
}
}

** 마지막으로 클라이언트 메인함수를 작성해 봅시다.

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 (단체 채팅 서버코드 예제)