JAVA NIO 소켓 통신

서버소켓 만들고 연결


		try {

			serverSocketChannel = ServerSocketChannel.open();
			serverSocketChannel.socket().bind(new InetSocketAddress(5050));

			boolean bLoop = true;

			while (bLoop) {
				try {
					socketChannel = serverSocketChannel.accept();
					socketChannel.configureBlocking(true);

					logger.info("[ESMLC Listen[" + "] 5050 port Socket Accept EsmlcIfWorkThread Start");

					socketWork(socketChannel);

				} catch (Exception e) {
					e.printStackTrace();
					try {
						Thread.sleep(5000);
					} catch (InterruptedException e1) {
						e1.printStackTrace();
					}
				}

				try {
					Thread.sleep(50);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}

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

읽기 && 쓰기

		ByteBuffer writeBuf = ByteBuffer.allocate(1024);
		ByteBuffer readBuf = ByteBuffer.allocate(10);

		Charset charset = Charset.forName("UTF-8");

		boolean bConnect = true;
		while (bConnect) {

			int byteCount = 0;
			byte[] readByteArr;

			String data = "";

			try {
				// SocketChannel open
				logger.debug("HL7 protocol 전송");

				// writeBuf.clear();
				writeBuf.put(data.getBytes("UTF-8"));
				writeBuf.flip();
				while (writeBuf.hasRemaining()) {

					logger.debug("SocketChannel open-3");
					socketChannel.write(writeBuf); //쓰기
				}

				
				if(읽기 상황일시) {
					
					int bytesRead = socketChannel.read(readBuf); 
					while (bytesRead != -1) {// 만약 소켓채널을 통해 buffer에 데이터를 받아왔으면

						readBuf.flip(); // make buffer ready for read
						// 10240로 정의한 buffer의 크기를 실제 데이터의 크기로 flip() 함

						while (readBuf.hasRemaining()) {
							// System.out.print((char) readBuf.get()); // read 1 byte at a time
							data = data + String.valueOf(((char) readBuf.get()));
						}

						// logger.debug("읽기 끝 " + bytesRead);
						readBuf.clear(); //make buffer ready for writing
						bytesRead = socketChannel.read(readBuf);
					}

					logger.debug("-------------- 응답 data ----------------");
					logger.debug(data);

					parsingHl7toJson(data, writeBuf);
														
				}
				
				

				bConnect = false;
				// socketChannel.close(); //AsynchronousCloseException 이 발생하지 않기 위해서
				logger.debug("[## ##][#3 Socket Connect");

			} catch (IOException e) {
				// e.printStackTrace();
				logger.debug("[####][#4 Not Connected!!! IO Exception Occured");
			}
		} // while
		logger.debug("[## ##][#5 Socket send complete");










좋은 웹페이지 즐겨찾기