Java TCP/IP 소켓 통신 예제(Client)

telnet ip port

서버로 보내는 메시지

client > server: 서버로 보내는 메시지
client < server: 서버에서 보낸 응답

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Scanner;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.gson.JsonObject;

/**
 * @authoer	aaboo. 202211.15
 * @usage
 * 		SocketClient socketClient = new SocketClient(ip, port);
 * 		String returnMsg = socketClient.send("서버로 보낸 메시지");
 * @인코딩 변경 방법
 * 		socketClient.setEncoding("UTF-8");
 * 		socketClient.setReqEncoding("UTF-8");
 * 		socketClient.setResEncoding("EUC-KR");
 */
public class SocketClient {

	private static final Logger logger = LoggerFactory.getLogger(SocketClient.class);
	
	//보내기 받기 인코딩
	private String ip;
	private String port;
	private String reqEncoding = "UTF-8";
	private String resEncoding = "UTF-8";
	
	//통신준비
	private Socket socket = null;
	private OutputStream outputStream = null;
	private InputStream inputStream = null;
	private InputStreamReader inputStreamReader = null;
	private BufferedReader bufferedReader = null;
	
	//생성자
	public SocketClient(){}
	public SocketClient(String ip, int port){
		init(ip, port);
		open();
	}
	public SocketClient(String ip, String port){
		init(ip, Integer.parseInt(port));
		open();
	}
	//소켓 정보 생성
	public void init(String ip, int port) {
		this.ip = ip;
		this.port = String.valueOf(port);
	}
	//소켓 연결 및 스트림 생성
	public void open() {
		try {
			//소켓서버 연결
			this.socket = new Socket(this.ip, Integer.parseInt(this.port));
			logger.info("Socket Server["+ this.ip +":"+ this.port+"] Connected!");	
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	//소켓 연결 및 스트림 생성
	public void open(String ip, int port) {
		init(ip, port);
		open();
	}
	//닫기
	private void close() {
		socketClose();
		streamClose();
	}
	//소켓 닫기
	private void socketClose() {
		try {
			if(!socket.isClosed()) {
				logger.info("Socket Server["+ this.ip +":"+ this.port+"] Closed!");	
				socket.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			this.ip = null;
			this.port = null;
			this.socket = null;
		}
	}
	//스트림 닫기
	private void streamClose() {
		try {
			if(outputStream!=null) outputStream.close();
			if(inputStreamReader!=null) inputStreamReader.close();
			if(bufferedReader!=null) bufferedReader.close();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			this.outputStream = null;
			this.inputStreamReader = null;
			this.bufferedReader = null;
		}
	}

	//소켓에 메시지 전송 및 응답받기
	private String write(String msg) {	
		logger.info("client > server: {}", msg);	
		String responseMessage = "";
		try {
			//Client에서 소켓서버로 요청
			this.outputStream = socket.getOutputStream();
			this.outputStream.write(msg.getBytes(this.reqEncoding));
			this.outputStream.flush();
			//소켓서버에서 Client로 응답
			this.inputStreamReader = new InputStreamReader(socket.getInputStream(), this.resEncoding);
			this.bufferedReader = new BufferedReader(this.inputStreamReader);
			responseMessage = bufferedReader.readLine();
			logger.info("client < server: {}", responseMessage.toString());	
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return responseMessage;
	}
	//메시지 보내고 소켓 닫기
	private String writeAndClose(String msg) {	
		String responseMessage = write(msg);
		close();
		return responseMessage;
	}
	/**
	 * 인코딩
	 */
	//보내기 받기 문자인코딩 처리
	public void setEncoding(String encoding) {
		setReqEncoding(encoding);
		setResEncoding(encoding);
	}
	public void setReqEncoding(String reqEncoding) {
		this.reqEncoding = reqEncoding;
	}
	public void setResEncoding(String resEncoding) {
		this.resEncoding = resEncoding;
	}
	
	/**
	 * 실사용
	 */
	//소켓열고, 메시지 보내고, 닫기
	public String send(String ip, int port, String msg) {
		open(ip, port);			
		return writeAndClose(msg);
	}
	//메시지 보내고(open 먼저 선실행 필요), 닫기
	public String send(String msg) {		
		return writeAndClose(msg);
	}
	//소켓열고, 메시지 보내고, 닫지 않기
	public String sending(String ip, int port, String msg) {
		open(ip, port);			
		return write(msg);
	}
	//메시지 보내고(open 먼저 선실행 필요), 닫지 않기
	public String sending(String msg) {		
		return write(msg);
	}
}


댓글 남기기