Server
package socket;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.NoSuchElementException;
import java.util.Scanner;
public class Ex02_Server {
public static void main(String[] args) {
ServerSocket ss = null;
Socket so = null;
Scanner sc = null;
String msg = null;
try {
ss = new ServerSocket(7777);
System.out.println("[Server] 접속 대기중...");
so = ss.accept(); // Listen
System.out.println("[Server] " + so.getInetAddress() + "에서 접속함");
sc = new Scanner(so.getInputStream());
while(true) {
msg = sc.nextLine();
System.out.println(msg);
if("종료".equals(msg)) {
break;
}
}
System.out.println("[Server] 상대측에서 종료했습니다");
} catch (NoSuchElementException e) {
System.out.println("[Server] 상대측에서 종료했습니다");
} catch (IOException e) {
e.printStackTrace();
} finally {
try { if(sc != null) sc.close(); } catch(Exception e) {}
try { if(so != null) so.close(); } catch(Exception e) {}
try { if(ss != null) ss.close(); } catch(Exception e) {}
}
}
}
Client
package socket;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;
public class Ex02_Client {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Socket so = null;
PrintWriter pw = null;
String msg;
try {
so = new Socket("192.168.112.20", 7777);
pw = new PrintWriter(so.getOutputStream());
while(true) {
System.out.print("서버에게 보낼 메시지 입력 : ");
msg = sc.nextLine();
pw.println(msg);
pw.flush();
if("종료".equals(msg)) {
break;
}
} // end of while
System.out.println("종료했습니다");
} catch (IOException e) {
e.printStackTrace();
} finally {
try { if(sc != null) sc.close(); } catch(Exception e) {}
try { if(so != null) so.close(); } catch(Exception e) {}
}
}
}
'AWS CLOUD FRAMEWORK > Java' 카테고리의 다른 글
[Day18] Chat (0) | 2023.04.07 |
---|---|
[Day18] Ex03 (0) | 2023.04.07 |
[Day18] Ex01 (0) | 2023.04.07 |
[Day18] Ex01_Server (0) | 2023.04.07 |
[Day17] Quiz (0) | 2023.04.06 |