Read Byte Array from Server send Client [Socket]


Note :  Message \f  Message \f.

ClientSearch.java

package com.thaihoanghai.action;

import java.io.IOException;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.util.List;
import java.util.StringTokenizer;

public class ClientSearch {
	public static String TIMEOUT = "30000";
	public static String PORT_PROBE = "7890";
	public static String HOST_IP = "localhost";
	public final static String MESSAGE = "received";

	private ClientSearch()
	{
		//================
	}

	public static void main(String[] args) {
		// Check parameter
		try {
			//The destination port number
			int tester_port = Integer.parseInt(ClientSearch.PORT_PROBE);
			String tester_host = ClientSearch.HOST_IP;

			String searchMessage = "Select * from employee";
			//=======================================================
			// execute
			executeSearch(tester_host, tester_port, searchMessage);
		}catch (Exception e){

		}
	}

	/**
	 * Method used send message and receive message from server
	 * @param hostIP : Host IP address
	 * @param cf_port : Port open connect to server
	 * @param args : message send to server
	 * @throws IOException :
	 * @throws SocketTimeoutException
	 * @throws Exception
	 */
	private synchronized static void executeSearch(String hostIP, int cf_port, String args)
			throws IOException, SocketTimeoutException, Exception {

		Socket f_socket = null;
		MessageTransceiver f_transceiver = null;

		try {
			// ----- Open socket
			f_socket = new Socket(hostIP, cf_port);

			// I prepare the message transceiver
			f_transceiver = new MessageTransceiver(f_socket);

			//The error If you can not open socket
		} catch (IOException e) {
			e.printStackTrace();
		}
		try {
			// ----- Timeout period
			int time_out = 0;
			time_out = Integer.parseInt(ClientSearch.TIMEOUT);

			// ----- Timeout time setting
			f_transceiver.setTimeout(time_out);

			@SuppressWarnings("unused")
			List<String> dataReceived = null;

			//----- Sending request
			f_transceiver.send(args);

			// ----- Request send OK response received
			dataReceived = f_transceiver.receive();

		} catch (SocketTimeoutException e) {
			throw new Exception("Time Out Exception !!!!");
		} catch (IOException e) {
			throw new Exception("Error !!!" + e.toString());
		} catch (Exception e) {

		} finally {
			try {
				// Closing a clear and client socket of the input and output stream
				if (f_transceiver != null) {
					f_transceiver.close();
				}
			}
			catch (IOException e) {

			}
		}
	}

	/**
	 * Method used to test : Output data ...........
	 * @param listData
	 */
	@SuppressWarnings("unused")
	private static void readDataReceived(List<String> listData){
		String header = listData.get(0);
		StringTokenizer tokenHeader = new StringTokenizer(header, ",");
		// Process for Header
		//==============================================================
		// Skip item at position 1...
		for (int i = 1; i < listData.size()-1; i++) {
			String data = listData.get(i);
			System.out.println(data);
		}

	}

}

Class MessageTransceiver.java

package com.thaihoanghai.action;

import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.List;

public class MessageTransceiver {
	protected Socket f_socket = null;
	/** Socket output stream **/
	protected DataOutputStream sockdos = null;
	/** Socket input stream **/
	protected DataInputStream sockdis = null;
	/** Timeout period (in milliseconds ) */
	protected int f_timeout = 0;

	public final static String DATA_RES = "OK!!";
	public final static String DATA_END = "End!";

	private static final byte LF = 0x0A;
	/**
	 * The constant indicate end of a line (window).
	 */

	private static final byte CNULL = '\f';

	/**
	 * Constructor
	 *    @param    a_socket	Connected socket
	 *    @throws   NullPointerException
	 */
	public MessageTransceiver(Socket a_socket) throws IOException {

		// ----- Parameter check
		if (a_socket == null) {
			String msg = "Socket is null.";
			throw new NullPointerException(msg);
		}

		//----- Set the instance field parameters
		f_socket = a_socket;
		int lPort =f_socket.getPort();
		//----- Socket input and output stream generation
		try {
			//----- Generate the data stream output from the output stream of the socket
			sockdos = new DataOutputStream(f_socket.getOutputStream());
			//----- Generate a data input stream from the input stream of the socket
			sockdis = new DataInputStream(f_socket.getInputStream());
		} catch (IOException ioe) {
			throw ioe;
		}
		System.out.println("Port Socket : " + lPort);
	}

	/**
	 *  set the time-out period .
	 *    @param    a_timeout	Time-out period
	 *    @throws   IllegalArgumentException	Time-out if the number is negative
	 */
	public synchronized void setTimeout(int a_timeout) throws IllegalArgumentException {
		//----- Parameter check
		if (a_timeout < 0) {
			String msg = "Timeout time is a negative number.";
			throw new IllegalArgumentException(msg);
		}

		//----- Set to an instance field parameters
		f_timeout = a_timeout;
	}

	/**
	 *  I will send the message .
	 *    @param    message	Message to be sent
	 *    @throws   Exception	Failure to send a message
	 */
	public void send(String message) throws Exception {
		try {
			// prepare a byte array output stream
			ByteArrayOutputStream baos = new ByteArrayOutputStream();

			//----- Convert into a byte array message
			baos.write( message.toString().getBytes(), 0, message.length() );
			baos.flush();
			// ----- Data transmission
			baos.writeTo(sockdos);
			sockdos.flush();
			baos.close();
			//Close object output stream
			// Note: Sockets that are closed when you close the DataOutputStream, is not closed here
			// In addition , closed unnecessary ByteArrayOutputStream
		} catch (Exception e){
			throw e ;
		}

	}

	/**
	 *  Returns receives the message from the stream of the socket .
	 *  Or return null if the received data is not a message ,
	 *  Or I will throw a ClassNotFoundException.
	 *  In addition , it throws an SocketTimeoutException If you have time-out .
	 *    @return   String 		Message
	 *    @throws   SocketTimeoutException	If you have time-out
	 *    @throws   ClassNotFoundException	If the received data is not the message
	 *    @throws   IOException	If it fails to receive the message
	 */
	public synchronized List<String> receive() throws	SocketTimeoutException, IOException, Exception {
		List<String> data = new ArrayList<String>();

		f_socket.setSoTimeout(f_timeout);

		int buffMax = f_socket.getReceiveBufferSize();

		final byte[] lineBuffer = new byte[1000];
		int lineIndex;
		byte b;
		int count;
		// buffer size when read socket
		int bufferSize = buffMax;
		int numRemainBytes = 0;

		byte[] remainBuffer = null;
		//final ByteBuffer buffer = ByteBuffer.allocate(bufferSize);
		byte[] buffer = new byte[bufferSize];

		do {
			//Read one block
			count = sockdis.read(buffer);

			//Have data => Process it
			if (0 < count) {
				lineIndex = 0;
				//Still remain bytes of previous block?
				if (0 < numRemainBytes) {
					for (int i = 0; i < numRemainBytes; i++) {
						lineBuffer[lineIndex++] = remainBuffer[i];
					}
					numRemainBytes = 0;
				}
				int marker = 0;
				//Get lines from current block
				for (int i = 0; i < count; i++) {
					b = buffer[i];
					lineBuffer[lineIndex++] = b;
					//End line?
							// if (b == LF || b == CRLF) {
					if (LF == b || CNULL == b) {
						//Get fields of a line
						//                         final List<String> fields = getFieldsOfLine(lineBuffer, 0, lineIndex);
						String line = new String(lineBuffer, 0, lineIndex, "UTF8").trim();
						data.add(line);
						System.out.println(line);
						//Reset for next line
						lineIndex = 0;
						marker = i + 1;
					}
				}
				numRemainBytes = count - marker;
				//Still remaining bytes => Keep them
				// if (numRemainBytes > 0) {
				if (0 < numRemainBytes) {
					int index  = 0;
					remainBuffer = new byte[numRemainBytes];
					for (int i = marker; i < count; i++) {
						b = buffer[i];
						remainBuffer[index++] = b;
					}
				}
			}
			//Reset for next block (if any)
			if (-1 != count) {
				buffer = new byte[bufferSize];
			}
		} while (-1 != count);

		return data;
	}

	/**
	 *  I will close the client socket and input and output stream .
	 *    @throws   IOException
	 *              If you have failed to close the input and output stream
	 *              If you fail to close the client socket
	 */
	public void close() throws IOException {
		try {
			if (sockdos != null) {
				sockdos.close();
				sockdos = null;
			}
			if (sockdis != null) {
				sockdis.close();
				sockdis = null;
			}
			if (f_socket != null) {
				f_socket.close();
				f_socket = null;
			}
		} catch (IOException ioe) {

			throw ioe;
		}
	}
}

Class server


package thaihoanghai.server;

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

public class ServerTest {
	public static void main(String[] args) throws IOException {
		ServerSocket server = new ServerSocket(7890);

		while(true){
			Socket sc = server.accept();
			InputStream in = sc.getInputStream();

			byte[] buffer  = new byte[1024];
			int read = in.read(buffer);
			String str = new String(buffer, 0 , buffer.length);
			System.out.println(str);
			if(str != ""){
				OutputStream socketOutputStream = sc.getOutputStream();
				socketOutputStream.write("Header=ABC-DDEE=EEEE\fData1=Hello World 1;\fData2=Hello World 2\fEOF;\fRESULT_CODE=OK\f".getBytes());
				socketOutputStream.close();
			}
		}
	}
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: