네트워크 상에서 컴퓨터를 식별하는 번호로 네트워크 어댑터(랜카드)마다 할당 되어 있음
같은 컴퓨터 내에서 프로그램을 식별하는 번호로
클라이언트는 서버 연결 요청 시 IP주소와 포트 번호를 알아야 함
요청(Requst) - req로 사용
응답(Response) - res로 사용
여러대의 컴퓨터를 통신 회선으로 연결한 것
소켓(Socket)
프로토콜(Protocol)
TCP(Transmission Control Protocol) (은행, 기차예매...)
UDP(User Datagram Protocol) (스트리밍서비스,...)
public void serverStart() {
int port = 8500;
ServerSocket serverSocket = null;
Socket client = null;
InputStream is = null;
BufferedReader br = null;
OutputStream os = null;
PrintWriter pw = null;
try {
serverSocket = new ServerSocket(); // 소켓 객체 생성
client = serverSocket.accept(); // 연결
String clientIP = client.getInetAddress().getHostAddress(); // Client IP주소
is = client.getInputStream(); // 클라이언트에서 입력받기
os = client.getOutputStream(); // 클라이언트에게 출력하기
// Socket에 있는 메서드 사용
//InputStreamReader : 바이트기반 스트림과 문자기반 스트림 연결에 사용하는 스트림
br = new BufferedReader(new InputStreamReader(is));
pw = new PrintWriter(os);
pw.println("무슨일이야");
pw.flush(); // 스트림 내용 밀어내기
String str = br.readLine(); // 클라이언트 내용 불러오기
System.out.println(str);
} catch(IOException e) {
e.printStackTrace();
} finally {
try {
if(serverSocket != null) serverSocket.close();
if(client != null) client.close();
if(br != null) br.close();
if(pw != null) pw.close();
} catch(IOException e) {
e.printStackTrace();
}
}
}
//3. 보조 스트림을 통해 성능 개선
br = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
pw = new PrintWriter(clientSocket.getOutputStream());