package ch03_chat;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
public class ChatServer {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// 서버
ServerSocket listener = null;
Socket socket = null;
BufferedReader sin = null;
BufferedWriter sout = null;
try {
listener = new ServerSocket(10000); // 서버 소켓 생성
System.out.println("- Server 준비 -");
socket = listener.accept(); // 클라이언트로 부터 연결 요청 대기
sin = new BufferedReader(new InputStreamReader(socket.getInputStream())); // 서버 수신
sout = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));// 서버 송신
String inputMessage = null;
while(true) {
inputMessage = sin.readLine(); // 클라이언트가 전송한 데이터 읽기
if(inputMessage.equals("end")) {
System.out.println("- 연결 종료 -");
break;
}
System.out.println("sin : " + inputMessage);
System.out.println();
System.out.print("서버 입력 > ");
String outputMessage = scanner.nextLine();
sout.write(outputMessage + "\\n");
sout.flush();
}
} catch (Exception e) {
System.out.println("서버 error~");
} finally {
try {
if(sout != null) sout.close();
if(sin != null) sin.close();
if(socket != null) socket.close();
if(listener != null) listener.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
package ch03_chat;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.util.Scanner;
public class ChatClient {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// 클라이언트
Socket socket = null;
BufferedReader cin = null;
BufferedWriter cout = null;
try {
socket = new Socket("localhost", 10000);
System.out.println("서버 연결...");
cin = new BufferedReader(new InputStreamReader(socket.getInputStream())); // 클라이언트 수신
cout = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())); // 클라이언트 송신
String outputMessage = null;
while(true) {
System.out.print("클라이언트 입력 > ");
outputMessage = scanner.nextLine();
if(outputMessage.equals("end")) {
cout.write(outputMessage + "\\n");
cout.flush();
break;
}
cout.write(outputMessage + "\\n");
cout.flush();
System.out.println();
String inputMessage = cin.readLine(); // 서버가 전송한 데이터
System.out.println("cin : " + inputMessage);
}
} catch (Exception e) {
System.out.println("클라이언트 error~");
} finally {
try {
if(cin != null) cin.close();
if(cout != null) cout.close();
if(socket != null) socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}