[JAVA] 소켓(Socket) 통신 채팅 프로그램 만들기

JoJo·2023년 7월 17일
0

💡 서버/클라이언트 소켓 연결 후 Stream 으로 데이터 보내기


✔️ 결과 화면

✔️ 서버 소켓(Server Socket) 소스코드

package com.kh.day16.network.exam3;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

public class ChattingServer {

	public static void main(String[] args) {
		ServerSocket serverSorket = null;	// ServerSocket 초기화
		
		InputStream is = null;				// InputStream 선언(데이터 받기위해서)
		OutputStream os = null;				// InputStream 선언(데이터 보내기위해서)
		Scanner sc = new Scanner(System.in);
		
		try {
			serverSorket = new ServerSocket(7777);	// 포트번호 생성
			System.out.println("클라이언트 접속 대기중...");
			Socket socket = serverSorket.accept();	// 클라이언트 접속 대기 후 연결되면 바로 연결
			System.out.println("클라이언트 접속 완료");
			// 2. 데이터 받기
			is = socket.getInputStream();
			byte [] bytes = new byte[1024];		// 바이트로 받아야함
			int readByteNo = is.read(bytes);	// 바이트로 읽은 메세지 변수에 저장
			String message = new String(bytes, 0, readByteNo);	// 저장한 변수 메시지 읽기
			System.out.printf("클라이언트(상대) : %s\n", message);
			//====================== 받기 완료 ======================
			// 3. 데이터 보내기
			os = socket.getOutputStream();
			System.out.print("서버(나) : ");
			message = sc.nextLine();
			bytes = message.getBytes();
			os.write(bytes);
			os.flush();
			System.out.println("데이터 전송 성공!");
			
		} catch (IOException e) {
			e.printStackTrace();
		}	
	}
}

✔️ 클라이언트 소켓(Client Socket) 소스코드

package com.kh.day16.network.exam3;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;

public class ChattingClient {

	public static void main(String[] args) {
		String address = "127.0.0.1";	// server ip 주소 변수 저장
		int port = 7777;				// server 포트 주소 변수 저장
		
		OutputStream os = null;				// InputStream 선언(데이터 보내기위해서)
		InputStream is = null;				// InputStream 선언(데이터 받기위해서)
		Scanner sc = new Scanner(System.in);
		
		try {
			System.out.println("연결 요청중...");
			Socket socket = new Socket(address, port);	// 소켓 생성 -> 서버 ip, 포트 번호 입력
			System.out.println("연결 성공!");
			// 1. 데이터 보내기
			os = socket.getOutputStream();
			System.out.print("클라이언트(나) : ");	// 가이드 메세지
			String message = sc.nextLine();			// 보낼 메세지
			byte [] bytes = message.getBytes();		// byte 타입으로 메세지 보내기
			os.write(bytes);	// OutputStream 에 메세지 넣기
			os.flush();			// 메세지 내보내기
			System.out.println("데이터 전송 완료!");
			//====================== 보내기 완료 ======================
			// 4. 데이터 받기
			is = socket.getInputStream();
			bytes = new byte[1024];
			int readByteNo = is.read(bytes);
			message = new String(bytes, 0, readByteNo);
			System.out.printf("서버(상대) : %s\n", message);
			
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}



💡 1:1 채팅 프로그램 만들기


✔️ 결과 화면


✔️ 서버 소켓(Server Socket) 소스코드

package com.kh.day16.network.exercise1;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

public class ChattingSever {

	public static void main(String[] args) {
		
		ServerSocket serverSocket = null;
		OutputStream os = null;
		InputStream is = null;
		Scanner sc = new Scanner(System.in);
		
		try {
			// 포트번호 설정 후 연결 대기
			serverSocket = new ServerSocket(7777);
			System.out.println("클라이언트 연결 대기중...");
			Socket socket = serverSocket.accept();
			// 연결 된 후에는 소켓 객체 생성
			System.out.println("클라이언트 접속 완료");
			
			is = socket.getInputStream();	// 한번만 생성되면 됨. 반복 필요 없음
			os = socket.getOutputStream();	// 한번만 생성되면 됨. 반복 필요 없음
			
			while(true) {
				// 2. 데이터 받기
				// 프로그램 기준 들어오니까 InputStream
				byte [] bytes = new byte[1024];
				// 읽은 때에는 read() 메소드 사용
				int readByteNo = is.read(bytes);
				// bytes에는 읽은 데이터, readByteNo 는 읽은 갯수
				// byte로 출력할 수 없어서 문자열로 만들어줌.
				String message = new String(bytes, 0, readByteNo);
				System.out.printf("클라이언트(상대) : %s\n", message);
				
				// 3. 데이터 보내기
				// 프로그램 기준 나가니까 OutputStream
				System.out.print("서버(나) : ");
				message = sc.nextLine();
				bytes = message.getBytes();
				os.write(bytes);
				os.flush();
				// ============== 보내기 완료 ==============
			}
			
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
}

✔️ 클라이언트 소켓(Client Socket) 소스코드

package com.kh.day16.network.exercise1;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;

public class ClientServer {

	public static void main(String[] args) {
		String address = "192.168.60.217";
		int port = 6312;
		
		OutputStream os = null;
		InputStream is = null;
		Scanner sc = new Scanner(System.in);
		
		try {
			System.out.println("연결 요청중...");
			// 설정된 IP, PORT에 연결 요청함.
			Socket socket = new Socket(address, port);
			// 연결 된 후에는 소켓 객체 생성
			System.out.println("연결 성공");
			
			os = socket.getOutputStream();	// 한번만 생성되면 됨. 반복 필요 없음
			is = socket.getInputStream();	// 한번만 생성되면 됨. 반복 필요 없음
			
			while(true) {
				// 1. 데이터 보내기
				// 프로그램 기준 나가니까 OutputStream
				System.out.print("클라이언트(나) : ");
				String message = sc.nextLine();
				byte [] bytes = message.getBytes();
				// 보낼때 버퍼에 씀 write() 메소드 사용
				os.write(bytes);
				// 버퍼 비워주기 flush()!
				os.flush();
				// 4. 데이터 받기
				// 프로그램 기준 들어오니까 InputStream
				bytes = new byte[1024];
				int readByteNo = is.read(bytes);
				message = new String(bytes, 0, readByteNo);
				System.out.printf("서버(상대) : %s\n", message);
			}

		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
profile
꾸준히

1개의 댓글

comment-user-thumbnail
2023년 7월 18일

정말 좋은 정보 감사합니다!

답글 달기