Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | ||||
4 | 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 | 16 | 17 |
18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 26 | 27 | 28 | 29 | 30 | 31 |
Tags
- GIT
- AssertJ
- 스프링부트
- StringBuilder
- array
- JS
- 파이썬
- 객체
- JavaScript
- class
- Python
- 저장소
- 메소드
- docker
- Dict
- SSL
- 프로그래머스스쿨
- 자바스크립트
- Swing
- Docker Desktop
- Java
- SpringBoot
- 클래스
- join()
- 배열
- event
- c#
- synchronized
- 자바
- thread
Archives
- Today
- Total
정리노트
[자바/java] 서버, 클라이언트 접속 (간단한 채팅) / TCP 프로토콜 본문
1. 서버 만들기
package serverSocket;
import java.io.*;
import java.net.*;
import java.util.Scanner;
public class ServerSocketTest {
public static void main(String[] args) {
ServerSocket serverSocket = null;
Socket clientSocket = null;
BufferedReader in = null;
PrintWriter out = null;
Scanner sc = new Scanner(System.in);
try {
serverSocket = new ServerSocket(5000); // 연결포트생성, 포트 번호 : 5000 / ServerSocket(포트번호, 서버연결 대기 클라이언트 최대 개수<생략가능>)
System.out.println("연결을 기다리고 있음.");
clientSocket = serverSocket.accept(); // accept() -> 포트 연결 / 연결 시, 포트와 연결된 Socket 객체 반환
out = new PrintWriter(clientSocket.getOutputStream()); // 클라이언트로 내용 내보냄
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); // 클라이언트에게서 내용을 받음
System.out.println("클라이언트와 연결이 되었습니다.");
while(true) {
String msg = in.readLine();
if (msg.equalsIgnoreCase("quit")) {
System.out.println("클라이언트가 연결을 종료하였습니다.");
break;
}
System.out.println("클라이언트가 보낸 문자열: " + msg);
System.out.print("클라이언트로 보낼 문자열을 입력 후 Enter: ");
String omsg = sc.nextLine();
out.write(omsg + "\n");
out.flush(); // 버퍼비우기
}
out.close();
clientSocket.close();
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
2. 클라이언트 만들기
package serverSocket;
import java.io.*;
import java.net.Socket;
import java.util.Scanner;
public class Client {
public static void main(String[] args) throws IOException {
Socket clientSocket = null;
BufferedReader in = null;
PrintWriter out = null;
final Scanner sc = new Scanner(System.in);
try {
clientSocket = new Socket("localhost", 5000); // 호스트이름, 5000번 소켓으로 연결.
out = new PrintWriter(clientSocket.getOutputStream());
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String msg;
while (true) {
System.out.print("서버로 보낼 문자열을 입력하고 엔터키를 누르세요: ");
msg = sc.nextLine();
if (msg.equalsIgnoreCase("quit")) {
out.println(msg);
out.flush(); // 버퍼비우기
break;
}
out.println(msg);
out.flush();
msg = in.readLine();
System.out.println("서버로부터 온 메시지: " + msg);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
out.close();
clientSocket.close();
}
}
}
728x90
'프로그래밍 > Java' 카테고리의 다른 글
[Java/연습] 프로그래머스 / 유연근무제 (0) | 2025.03.05 |
---|---|
[자바/java] 간단 채팅 프로그램 / UDP 서버, 클라이언트 (0) | 2023.02.07 |
[자바/java] IP주소 찾기 / 사이트 내용 받기 (0) | 2023.02.07 |
[자바/java] synchronized 데이터 중복사용 방지, 좌석예약 (0) | 2023.02.05 |
[자바/java] Thread 활용 두 개 이미지 이동 컨트롤 - 2 / join() (1) | 2023.02.05 |