JAVA 입문 시작
22.12.12(월) 네트워크
강준석
2022. 12. 12. 13:07
728x90
클라이언트/서버
OSI7계층
네트워크에 관련된 장비,규약은 회사마다 다 달랐음
그것의 표준을 맞춘것
1계층 - 물리계층
기계,전기,기능을 케이블로 전송
단순 주고받기만 함
장비:리피터,허브
2계층 - 데이터 링크 계층
정보의 전달
오류 검출
정보의 주고받는 단위 : 프레임
장비 : 브리지,스위치
3계층-네트워크 계층
안정성이 올라감,속도도 빠름
ip를 할당
4계층 - 전송 계층
통신이 활성화되는 계층
TCP 프로토콜을 사용
프로토콜 : 통신규약
TCP : 상호간 신뢰적인 연결지향 서비스를 제공
패킷(데이터를 보내는 단위) 손실 가능성이 적다,중복,순서 변경되는 경우가 없음
비연결 -> UDP
신뢰성이 낮음,비연결성
5계층- 세션계층
통신을 위한 논리적 연결을 해주는 계층
6계층-표현 계층
7계층 - 응용계층
서비스 제공
ip
port 번호
socket 연결해주는 장치
서버 동작 과정
1. 소켓 생성
2. 소켓 빈공간에 ip,port를 지정
3. 클라이언트 요청 대기
4. 요총 승인, 데이터 송수신 소켓 생성
5. 송수신
6. 연결종료
클라이언트 동작 과정
1. 소켓 생성
2. 서버에 요청 연결
3. 송수신
4. 연결 종료
예시
IP주소 불러오기
package 주소;
import java.net.InetAddress;
public class Sample01 {
public static void main(String[] args) {
try {
InetAddress local = InetAddress.getLocalHost();
System.out.println("내 컴퓨터 IP주소 : " + local.getHostAddress());
InetAddress[] iaArr = InetAddress.getAllByName("www.naver.com");
//IP주소가 1개가 아닐수도 있기에 배열을 사용
for (InetAddress r : iaArr) {
System.out.println("네이버 IP 주소 : " + r.getHostAddress());
}
} catch (Exception e) {
}
}
}
서버클래스만들기
package 소켓연결;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static void main(String[] args) {
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket();
// 1.소캣 생성
serverSocket.bind(new InetSocketAddress("localHost", 50005));
// 2.소켓 빈공간에 ip,port를 지정
while (true) {
// 3.클라이언트 요청 대기(서버는 기본으로 24시간 대기 상태 비슷한 환경을 만들기위해 무한반복문 사용)
System.out.println("[연결대기]");
Socket socket = serverSocket.accept();
InetSocketAddress isa = (InetSocketAddress) socket.getRemoteSocketAddress();
// 4.요청 승인, 데이터 송수신 소켓 생성
System.out.println("[연결수락] : " + isa.getHostName());
// 5.송수신
/* =========================메세지 주고받기============================ */
byte[] bytes = null; // byte단위로 주고받기때문
String message = null; // byte를 문자열로 형변환
InputStream is = socket.getInputStream();
bytes = new byte[100]; // client에서 받은 bytes를 배열방에 저장
int readByteCount = is.read(bytes);
message = new String(bytes, 0, readByteCount, "utf-8");
// 저장된 bytes를 문자열(String message)형태로 바꿈
System.out.println("[데이터 받음] : " + message);
OutputStream os = socket.getOutputStream();
message = "hi Client";
bytes = message.getBytes("utf-8");
os.write(bytes);
os.flush();
System.out.println("[데이터 전송함]");
is.close();
os.close();
socket.close();
/* =========================메세지 주고받기============================ */
}
} catch (Exception e) {
System.out.println("[연결실패]");
}
if (!serverSocket.isClosed()) {
try {
serverSocket.close();
} catch (Exception e) {
}
}
}
}
클라이언트 클래스만들기
package 소켓연결;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
public class Client {
public static void main(String[] args) {
Socket socket = null;
try {
socket=new Socket();
//1. 소켓 생성
System.out.println("[연결 요청]");
socket.connect(new InetSocketAddress("localhost",50005));
//2. 서버에 요청 연결
System.out.println("[연결 성공]");
//3. 송수신
/* =========================메세지 주고받기============================ */
byte[]bytes = null;
String message = null;
OutputStream os = socket.getOutputStream();
//연결된 소캣으로 server로 client를 아웃(보냄)
message = "hi Server";
bytes = message.getBytes("utf-8");
os.write(bytes); //server로 bytes 보냄
os.flush();
System.out.println("[데이터 전송함]");
InputStream is = socket.getInputStream();
bytes = new byte[100];
int readByteCount = is.read(bytes);
message = new String(bytes,0,readByteCount,"utf-8");
System.out.println("[데이터 받음]"+message);
os.close();
is.close();
/* =========================메세지 주고받기============================ */
}catch (Exception e) {
}
if(!socket.isClosed()) {
try {
socket.close();
}catch (Exception e) {
}
//4. 연결 종료
}
}
}
채팅하기
URL
ServerSocket
ip, port.번호(1~65550)중 하나를 정해야함
Socket
728x90