์๋ฒ - ํด๋ผ์ด์ธํธ๊ฐ ๋ฒ๊ฐ์์ ์ฑํ ํ ์ ์๋ ํ๋ก๊ทธ๋จ์ด๋ค.
ํด๋ผ์ด์ธํธ
package chat;
import java.io.*;
import java.net.*;
import java.util.*;
public 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.print("๋ณด๋ด๊ธฐ>>");
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){
System.out.println(e.getMessage());
}finally{
try{
sc.close();
if(socket != null) socket.close(); // ํด๋ผ์ด์ธํธ ์์ผ ๋ซ๊ธฐ
}catch(IOException e){
System.out.println("ํด๋ผ์ด์ธํธ ์ฑํ
์ค ์ค๋ฅ๊ฐ ๋ฐ์ํ์ต๋๋ค.");
}
}
}
}
์๋ฒ
package chat;
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 li = null;
Socket socket = null;
Scanner sc = new Scanner(System.in);
try{
li = new ServerSocket(9999);
System.out.println("์ฐ๊ฒฐ์ ๊ธฐ๋ค๋ฆฌ๋ ์ค .... ");
socket = li.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")){
System.out.println("ํด๋ผ์ด์ธํธ์์ bye๋ก ์ฐ๊ฒฐ์ข
๋ฃ");
break;
}
System.out.println("ํด๋ผ์ด์ธํธ: "+ inputMessage);
System.out.print("๋ณด๋ด๊ธฐ >> ");
String outputMessage = sc.nextLine();
out.write(outputMessage + "\n" );
out.flush();
}
} catch (IOException e){
System.out.println(e.getMessage());
}finally{
try{
sc.close();
socket.close(); //ํต์ ์ฉ ์์ผ ๋ซ๊ธฐ
li.close(); // ์๋ฒ ์์ผ ๋ซ๊ธฐ
}catch(IOException e){
System.out.println("ํด๋ผ์ด์ธํธ ์ฑํ
์ค ์ค๋ฅ๊ฐ ๋ฐ์ํ์ต๋๋ค.");
}
}
}
}