프로그래밍/Java
[자바/java] 서버, 클라이언트 접속 (간단한 채팅) / TCP 프로토콜
Rolen
2023. 2. 7. 20:04
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