본문 바로가기
개발 업무(코딩)-개발자였을때 썼던..

c(서버)와 java(클라이언트) socket 통신 간단 예제

by 주용사 2023. 1. 8.
728x90

서버는 TCPIP로 구현이 되어있고 거기에 붙어서 테스트해보기 위한 client모듈을 만들었다.

제일 고생한 것은, 서버로부터 받은 recieve데이터를 read할 때 고생했다. 데이터를 보낼때 정상적으로 보낸다음 또한번 newLine()으로 보냈기 때문에 받은 값은 null이였다.

데이터는 전부 char byte으로 내려 받는다.

spring legacy project에 있는 homecontroller에 수정해서 만든 소스이다.

@Controller
public class HomeController {

	private static final Logger logger = LoggerFactory.getLogger(HomeController.class);

	/**
	 * Simply selects the home view to render by returning its name.
	 * 
	 * @throws IOException
	 * @throws UnknownHostException
	 */
	@RequestMapping(value = "/", method = RequestMethod.GET)
	public String home(Locale locale, Model model) throws UnknownHostException, IOException {

		logger.info("Welcome home! The client locale is {}.", locale);

		Date date = new Date();
		DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);

		String formattedDate = dateFormat.format(date);

		model.addAttribute("serverTime", formattedDate);
		model.addAttribute("test", "hello");
		//////////////////////////////////////////////////////////////

		Socket socket = new Socket("IP", port);
		// socket.
		 socket.setSoTimeout(5000); // 5초
		// 링거타임 설정 0, 소켓을 닫을 때 아직 전송되지 않은 패킷이 있다면 이를 버리고 소켓을 즉시 닫음
		socket.setSoLinger(true, 0);
		
		OutputStream os = null;
		OutputStreamWriter osw = null;
		BufferedWriter bw = null;

		InputStream is = null;
		InputStreamReader isr = null;

		try {
			os = socket.getOutputStream();
			osw = new OutputStreamWriter(os);
			bw = new BufferedWriter(osw);

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		String TCP_DATA_HEAD;

		String sLength = "00133"; /* Data 길이 */
		String sLineFlag = "A"; /* 부문 구분(A~U) */
		String sResponseCode = "    "; /* 응답코드 */
		String sTrCode = "1003"; /* data type */

		TCP_DATA_HEAD = sLength + sLineFlag + sResponseCode + sTrCode + sNextGb;

		String body;
		String FinalData;

		String index = "     ";
		String filler = "                                             ";
		String count = "001";

		body = index + filler + count;

		FinalData = TCP_DATA_HEAD + body;
		model.addAttribute("data", "{" + FinalData + "}");
		model.addAttribute("length", FinalData.length());

		// head+index[5]+filler[45]+count[3]
		try {
			bw.write(FinalData, 0, FinalData.length()); // newLine()하면 안된다.
			bw.flush();

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		BufferedInputStream bis = new BufferedInputStream(socket.getInputStream());
		byte[] buff = new byte[1024];

		int read = 0;

		if (socket == null) {
			System.out.println("socket null");
		}

		read = bis.read(buff, 0, 1024);
		System.out.println("read = " + read);
		if (read < 0) {
			System.out.println("no data");
		}

		byte[] tempArr = new byte[1024];
		System.arraycopy(buff, 0, tempArr, 0, 1024);
		model.addAttribute("output", new String(tempArr));

		/*
		 bw.close(); 
		 osw.close(); 
		 os.close(); 
		 isr.close(); 
		 is.close();
		 */

		return "home";
	}
}
@Controller
public class HomeController {

	private static final Logger logger = LoggerFactory.getLogger(HomeController.class);

	/**
	 * Simply selects the home view to render by returning its name.
	 * 
	 * @throws IOException
	 * @throws UnknownHostException
	 */
	@RequestMapping(value = "/", method = RequestMethod.GET)
	public String home(Locale locale, Model model) throws UnknownHostException, IOException {

		logger.info("Welcome home! The client locale is {}.", locale);

		Date date = new Date();
		DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);

		String formattedDate = dateFormat.format(date);

		model.addAttribute("serverTime", formattedDate);
		model.addAttribute("test", "hello");
		//////////////////////////////////////////////////////////////

		Socket socket = new Socket("ip", port);
		// socket.
		 socket.setSoTimeout(5000); // 5초
		// 링거타임 설정 0, 소켓을 닫을 때 아직 전송되지 않은 패킷이 있다면 이를 버리고 소켓을 즉시 닫음
		socket.setSoLinger(true, 0);
		
		OutputStream os = null;
		OutputStreamWriter osw = null;
		BufferedWriter bw = null;

		InputStream is = null;
		InputStreamReader isr = null;

		try {
			os = socket.getOutputStream();
			osw = new OutputStreamWriter(os);
			bw = new BufferedWriter(osw);

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		String TCP_DATA_HEAD;

		String sLength = "00133"; /* Data 길이 */
		String sLineFlag = "A"; /* 부문 구분(A~U) */
		String sResponseCode = "    "; /* 응답코드 */
		String sTrCode = "1003"; /* data type */
		String sNextGb = "0"; /* 연속 구분 */
		String sReqsGb = "0"; /* 데이타 요청 구분 */
		String sWinId = "            "; /* Client Window ID */
		String sPcIdx = "   "; /* Client Index */
		String sPcIPAddr = "111.11.11.11   "; /* PC IP Address */
		String sNextPage = "0"; /* 연속 Page 존재여부 */
		String sUserId = "                    "; /* 사용자 Id */
		String sFiller = "             "; /* 예비 */

		TCP_DATA_HEAD = sLength + sLineFlag + sResponseCode + sTrCode + sNextGb + sReqsGb + sWinId + sPcIdx + sPcIPAddr
				+ sNextPage + sUserId + sFiller;

		String body;
		String FinalData;

		String index = "     ";
		String filler = "                                             ";
		String count = "010";

		body = index + filler + count;

		FinalData = TCP_DATA_HEAD + body;
		model.addAttribute("data", "{" + FinalData + "}");
		model.addAttribute("length", FinalData.length());

		// head+index[5]+filler[45]+count[3]
		try {
			bw.write(FinalData, 0, FinalData.length()); // newLine()하면 안된다.
			bw.flush();

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		BufferedInputStream bis = new BufferedInputStream(socket.getInputStream());
		
		// head[80] + index[5] + filler[45] + count[5] + sub[16]*alpha = 기본 151
		int read = 0;
		//TCP_DATA_HEAD의 길이값은 고정
		byte[] len = new byte[5];
		read = bis.read(len, 0, 5);
		int tcp_slength = Integer.parseInt(new String(len));
		System.out.println("test len = " + tcp_slength);
	
		byte[] buff = new byte[tcp_slength]; // 위에서 한번 짤랐기때문에 데이터길이를 제외하고 나온다.
		read = bis.read(buff, 0, buff.length); 
		System.out.println("body = " + read);
		if (read < 0) {
			System.out.println("no data");
		}
		String sbuff = new String(buff);
		
		model.addAttribute("output", sbuff);
		System.out.println(sbuff);
		
		System.out.println(sbuff.substring(0,1)); // sLineFlag[1]
		System.out.println(sbuff.substring(1,5)); // sResponseCode[4]
		System.out.println(sbuff.substring(5,9)); // sTrCode[4]
		System.out.println(sbuff.substring(9,10)); // sNextGb[1]
		System.out.println(sbuff.substring(10,11)); // sReqsGb[1]
		System.out.println(sbuff.substring(11,23)); // sWinId[12]
		System.out.println(sbuff.substring(23,26)); // sPcIdx[3]
		System.out.println(sbuff.substring(26,41)); // sPcIPAddr[15]
		System.out.println(sbuff.substring(41,42)); // sNextPage[1]
		System.out.println(sbuff.substring(42,62)); // sUserId[20]
		System.out.println(sbuff.substring(62,75)); // sFiller[13]
		System.out.println(sbuff.substring(75,80)); // body index[5]
		System.out.println(sbuff.substring(80,125)); // body filler[45]
		System.out.println(sbuff.substring(125,130)); // body count[5]
		
		int datacount = Integer.parseInt(sbuff.substring(125,130));
		for(int i = 0 ; i < datacount ; i++)
		{
			System.out.println("["+ sbuff.substring(130 + (i*16), 1 + sbuff.length() - (datacount-i)*16 ) + "]"); // body code[5]
		}
		/*
		 bw.close(); 
		 osw.close(); 
		 os.close(); 
		 isr.close(); 
		 is.close();
		 */

		return "home";
	}
}
728x90