import java.io.*;
import java.net.*;
import java.util.*;
public class ServerEx{
public static void main(String[] args) {
BufferedReader in = null;
BufferedWriter out = null;
ServerSocket listener = null;
Socket socket = null;
Scanner sc = new Scanner(System.in);
try {
listener = new ServerSocket(9999);
System.out.println("연결을 기다리는 중입니다....");
socket = listener.accept();
System.out.println("연결되었습니다.");
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
while(true) {
String inputMessage = in.readLine();
if(inputMessage.equalsIgnoreCase("bye")) {
break;
}
System.out.println("클라이언트: "+inputMessage);
System.out.println("보내기>>");
String outputMessage = sc.nextLine();
out.write(outputMessage+"\n");
out.flush();
}
} catch (IOException e) {
// TODO: handle exception
System.out.println(e.getMessage());
}finally {
try {
sc.close();
socket.close();
listener.close();
} catch (IOException e) {
// TODO: handle exception
System.out.println("에러");
}
}
}
}
import java.io.*;
import java.net.*;
import java.util.*;
class ClientEx{
public static void main(String[] args) {
BufferedReader in = null;
BufferedWriter out = null;
Socket socket = null;
Scanner sc = new Scanner(System.in);
try {
socket = new Socket("localhost",9999);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
while(true) {
System.out.println("모내기>>>");
String outputMessage = sc.nextLine();
if(outputMessage.equalsIgnoreCase("bye")) {
out.write(outputMessage+"\n");
out.flush();
break;
}
out.write(outputMessage + "\n");
out.flush();
String inputMessage= in.readLine();
System.out.println("서버: "+inputMessage);
} }catch (IOException e) {
// TODO: handle exception
System.out.println(e.getMessage());
}finally {
try {
sc.close();
if(socket != null)socket.close();
} catch (IOException e) {
// TODO: handle exception
System.out.println("서버와 채팅중 오류");
}
}
}
}