package com.my.tcp.server;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.BindException;
import java.net.ServerSocket;
import java.net.Socket;
public class ServerTest {
public static void main(String[] args) {
int port = 5432; // 포트번호 정하기, 0~1024는 예약된 포트니까 안쓰는게 좋다.
// 그 이후에 사용자 정의 포트번호
ServerSocket ss = null; //지역변수니까 초기값 null
Socket s = null;
InputStream is = null;
DataInputStream dis = null; //2번
OutputStream oos = null;// 에코
DataOutputStream dos = null;// 에코
try {
ss = new ServerSocket(port);
System.out.println("클라이언트 접속을 기다리기");
s = ss.accept();
is = s.getInputStream();
dis = new DataInputStream(is);
oos = s.getOutputStream();// 에코
dos = new DataOutputStream(oos);// 에코
// int readValue = is.read(); 1번
// System.out.println("클라이언트가 보낸 메시지:" + (char)readValue); 1번
// String readValue = dis.readUTF(); //2번
// System.out.println("클라이언트가 보낸 메시지:" + readValue); //2번
/* 3번
while(true) {
String receiveMsg = dis.readUTF();
if(receiveMsg.equals("quit")) {
break;
}
System.out.println("클라이언트가 보낸 메시지:" + receiveMsg);
} */
/* 3번 + break 안쓰는 코드로 변경
String receiveMsg;
while(!(receiveMsg = dis.readUTF()).equals("quit")) {
System.out.println("클라이언트가 보낸 메시지:" + receiveMsg);
}*/
// 에코
String receiveMsg;
while(!(receiveMsg = dis.readUTF()).equals("quit")) {
System.out.println("클라이언트가 보낸 메시지:" + receiveMsg);
dos.writeUTF(receiveMsg);
}
} catch (EOFException e) { // catch 사유 굳이 안적어도됨
} catch (BindException e) {
System.out.println(port + "포트가 이미 사용중입니다");
} catch (IOException e) {
e.printStackTrace();
} finally {
System.out.println("클라이언트와의 연결이 종료되었습니다");
if(s != null) {
try {
s.close();
} catch (IOException e) {
}
}
}
}
}
package com.my.tcp.client;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Scanner;
public class ClientTest {
public static void main(String[] args) {
Socket s = null; // 네트워크는 무조건 혼자 test해봐야함
String serverIP = "127.0.0.1"; // localhost, ip는 cmd창에서 확인
// String serverIP = "192.168.260.260.1"; // 없는 ip 입력해보기 UnknownHostException
// String serverIP = "192.168.1.83"; // 옆자리 컴퓨터
int serverPort = 5432;
OutputStream oos = null;
DataOutputStream dos = null;
InputStream is = null;//에코
DataInputStream dis = null; //에코
Scanner sc = new Scanner(System.in); // 3. 고정된 문자열말고 입력해서 보내기
try {
s = new Socket(serverIP, serverPort);
System.out.println("서버와 연결 성공");
oos = s.getOutputStream();
dos = new DataOutputStream(oos); // 2. 데이터 가공해서 보내기
// oos.write(65); // 1. 직접보내기
// dos.writeUTF("안녕하세요. 옆자리입니다"); // 2
is = s.getInputStream();//에코
dis = new DataInputStream(is);//에코
/*3번 방법
String sendMsg;
do { // 한번은 무조건 실행 -> while 참 -> 다시 do
System.out.print("서버로 보낼 메시지 (종료하려면 quit을 입력하세요.):");
sendMsg = sc.nextLine();
dos.writeUTF(sendMsg);
} while (!sendMsg.equals("quit"));*/
//에코
String sendMsg;
do { // 한번은 무조건 실행 -> while 참 -> 다시 do
System.out.print("서버로 보낼 메시지 (종료하려면 quit을 입력하세요.):");
sendMsg = sc.nextLine();
dos.writeUTF(sendMsg);
String receiveMsg = dis.readUTF();
System.out.println("서버가 되돌려준 메시지:" + receiveMsg);
} while (!sendMsg.equals("quit"));
} catch (EOFException e) {
e.printStackTrace();
} catch (UnknownHostException e) {
// e.printStackTrace(); 직접 노출하는건 좋은 방법이 아님
System.out.println(serverIP + " 서버는 존재하지 않습니다. 서버IP를 확인하세요");
} catch (ConnectException e) { // 자식예외
System.out.println("서버가 실행되지 않았습니다. 서버실행을 확인하세요");
} catch (SocketException e) { //부모예외
System.out.println("서버가 강제종료되었습니다. 서버확인하세요");
} catch (IOException e) {
e.printStackTrace();
} finally {
if(s != null) {
try {
s.close(); // oos나 dos close 안해도 소켓만 close하면 다 닫힘
// 각각 하고싶으면 dos.close(); -> oos.close(); -> s.close(); 생성된 순서 거꾸로 close해야함
} catch (IOException e) {
}
}
}
}
}