13 Ekim 2011 Perşembe

Reading formatted messages and extracting the real data coming through TCP socket

If the channel is kept alive between a client and a server then it is good to obey a messaging format for the communication between client and the server. Generally the obeyed format of the message can be as stated below:

START FLAG + LENGTH OF THE MESSAGE + MESSAGE BYTES + STOP FLAG

In the example below the start flag is assigned as 111999 and the stop flag is 999111. The server listens one or more clients and the reader threads extract the real messages coming from the clients. The method readUntilFlag does the real job for extracting the message.
package test;

import java.io.DataInputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

public class Application {

    public static void main(String[] args) throws IOException {
        int serverPort = 1111;
        ServerSocket serverSocket = new ServerSocket(serverPort);
        int clientId = 1;
        while (true) {
            Socket socket = serverSocket.accept();
            new ReaderThread(clientId++, socket).start();
        }
    }

    static class ReaderThread extends Thread{
        private int clientId;
        private Socket socket;

        ReaderThread(int clientId, Socket socket) {
            this.clientId = clientId;
            this.socket = socket;
        }

        public void run(){
            String message = null;
            while (!"exit".equalsIgnoreCase(message)) {
                try {
                    DataInputStream inputStream = new DataInputStream(socket.getInputStream());
                    readUntilFlag(inputStream, 111999);

                    int messageLength = inputStream.readInt();
                    byte[] messageBytes = new byte[messageLength];
                    inputStream.read(messageBytes, 0, messageLength);

                    readUntilFlag(inputStream, 999111);
                    message = new String(messageBytes);
                    System.out.println("Client " + clientId + " sent message: " + message + " to server...");
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void readUntilFlag(DataInputStream inputStream, int flag) {
        boolean found = false;
        byte[] flagBytes = intToByteArray(flag);
        try {
            byte tempBytes[] = new byte[4];
            tempBytes[0] = inputStream.readByte();
            tempBytes[1] = inputStream.readByte();
            tempBytes[2] = inputStream.readByte();
            tempBytes[3] = inputStream.readByte();
            // read until the flag is found
            while (!found) {
                if (flagBytes[0] == tempBytes[0] &&
                    flagBytes[1] == tempBytes[1] &&
                    flagBytes[2] == tempBytes[2] &&
                    flagBytes[3] == tempBytes[3]) {
                    found = true;
                } else {
                    tempBytes[0] = tempBytes[1];
                    tempBytes[1] = tempBytes[2];
                    tempBytes[2] = tempBytes[3];
                    tempBytes[3] = inputStream.readByte();
                }
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static byte[] intToByteArray(int value) {
        byte[] b = new byte[4];
        for (int i = 0; i < 4; i++) {
            int offset = (b.length - 1 - i) * 8;
            b[i] = (byte) ((value >>> offset) & 0xFF);
        }
        return b;
    }
}

Hiç yorum yok:

Yorum Gönder