반응형
cs지식을 늘리기 위해서 김영한 선생님의 java network programming 강의를 듣는 중이다.
Network Programming
기본적인 로직은 다음과 같다.
- 소켓서버 포트 지정
- 소켓서버 오픈
- 클라이언트 소켓서버에 접속
- 클라이언트 소켓서버에 데이터 송신
- 소켓서버는 클라이언트로 부터 데이터 수신
- 소켓서버가 클라이언트에게 데이터 송신
- 클라이언트는 소켓서버에서 데이터 수신
- 종료
Code
Client
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
public class Client {
private static final int PORT = 12345;
public static void main(String[] args) throws IOException {
MyLogger.log("client started");
//client socket 설정
Socket socket = new Socket("localhost",PORT);
//socket의 송수신 stream 설정
var input = new DataInputStream(socket.getInputStream());
var output = new DataOutputStream(socket.getOutputStream());
MyLogger.log("socket connect: "+socket);
//client socket 송신
String toSend = "Hello";
output.writeUTF(toSend);
MyLogger.log("client sent: "+toSend);
//client socket 수신
String recived = input.readUTF();
MyLogger.log("client recived: "+recived);
input.close();
output.close();
socket.close();
}
}
Socket Server
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
private static final int PORT = 12345;
public static void main(String[] args) throws IOException {
MyLogger.log("Server started");
//socket server open
ServerSocket serverSocket = new ServerSocket(PORT);
MyLogger.log("Server started :"+PORT);
//socket server wait
Socket socket = serverSocket.accept();
MyLogger.log("Client connected");
var input = new DataInputStream(socket.getInputStream());
var output = new DataOutputStream(socket.getOutputStream());
//socket server data recive
String recived = input.readUTF();
MyLogger.log("Client received : " + recived);
String tosend = "Hello World";
output.writeUTF(tosend);
//socekt server data send
MyLogger.log("Client sent : " + tosend);
input.close();
output.close();
socket.close();
}
}반응형
'JAVA' 카테고리의 다른 글
| 태태개발일지 - Java 파일 입출력 완전 정리 (0) | 2025.12.01 |
|---|---|
| 태태개발일지 - 김영한 java 고급 (람다) 람다 총정리 (0) | 2025.09.05 |
| 태태개발일지 - 김영한 java 고급 디폴트 메서드 (3) | 2025.08.11 |
| 태태코딩 - 김영한 고급 java 람다 (1) | 2025.07.29 |
| 태태개발일지 - 김영한 고급 JAVA LAMBDA (2) | 2025.07.28 |