IT/Java

java - Thread 적용전 채팅 소스

노마드오브 2018. 11. 22. 23:58

ServerEx.java

import java.io.BufferedReader;

import java.io.BufferedWriter;

import java.io.IOException;

import java.io.InputStreamReader;

import java.io.OutputStreamWriter;

import java.net.ServerSocket;

import java.net.Socket;

import java.util.Scanner;


public class ServerEx {


public static void main(String[] args) {

BufferedReader reader = null;

BufferedWriter writer = null;

Scanner scanner = new Scanner(System.in);  // 키보드 입력스트림

ServerSocket serverSocket = null;

Socket socket = null;

try {

serverSocket = new ServerSocket(9999);

System.out.println("연결을 기다리고 있습니다.");

socket = serverSocket.accept();

System.out.println("연결되었습니다.");

reader = new BufferedReader(new InputStreamReader(socket.getInputStream(), "utf-8"));

writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "utf-8"));

while (true) {

String inputMsg = reader.readLine();

if (inputMsg.equalsIgnoreCase("bye")) {

System.out.println("클라이언트에서 bye로 연결을 종료합니다");

break;

}

System.out.println("클라이언트: " + inputMsg);

System.out.println("보내기>>");

String outputMsg = scanner.nextLine();

writer.write(outputMsg + "\n");

writer.flush();

}

} catch (IOException e) {

e.printStackTrace();

} finally {

try {

reader.close();

writer.close();

scanner.close();

socket.close();

serverSocket.close();

} catch (IOException e) {

System.out.println("채팅 중 오류 발생");

}

}

} // main


}




ClientEx.java
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;

public class ClientEx {

public static void main(String[] args) {
BufferedReader reader = null;
BufferedWriter writer = null;
Socket socket = null;
Scanner scanner = new Scanner(System.in);
// try {
// BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in, "utf-8"));
// stdin.readLine();
//
// } catch (Exception e) {
// e.printStackTrace();
// }
try {
// 서버에 연결
socket = new Socket("127.0.0.1", 9999);
reader = new BufferedReader(new InputStreamReader(socket.getInputStream(), "utf-8"));
writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "utf-8"));
while (true) {
System.out.println("보내기>> ");
String outputMsg = scanner.nextLine();
writer.write(outputMsg + "\n");
writer.flush();
if (outputMsg.equalsIgnoreCase("bye")) {
break;
}
String inputMsg = reader.readLine();
System.out.println("서버: " + inputMsg);
}
} catch (Exception e) {
e.printStackTrace();
}

} // main()

}