从Channelbuffer中读取一个String

时间:2016-09-26 18:02:55

标签: java

我通过Socket将一个String发送到服务器。我实现了TCPClient类来模拟真实的场景。邮件始终以#开头,以##结尾。介于两者之间的一切都是信息。我只是在接收decodeMessage()内的流时尝试读取ASCii字符。因此,当读取包含35 Ascci代码的第一个字节时,我想在缓冲区中搜索消息##,它在ASCCII表中为3535。

如何从缓冲区中读取消息?

客户端

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.net.Socket;


public class TCPClient {

    public static void main(String argv[]) throws Exception {

        String message;
        String result;
        String aString = "#201601140000006#13534035454#1#0000#AUT#2#0000050000020027#114.034407,E,22.648272,N,,0.00,0.00#010104#004500#114.034407,E,22.648272,N,0.00,0.00#010104#004500##";
        // String aString = "###";
        BufferedReader inFromUser = new BufferedReader(new StringReader(aString));

        Socket clientSocket = new Socket("localhost", 39537);
        DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
        BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));

        message = inFromUser.readLine();
        outToServer.writeBytes(message + '\n');
        result = inFromServer.readLine();
        System.out.println(result);
        clientSocket.close();
    }
}

docodeMessage()

private Object decodeMessage(final ChannelBuffer buffer) {
    // Here with my String I am getting 160 for readableBytes.
    int readableBytes = buffer.readableBytes();
    if (readableBytes < 5) {
       //incase the messagejust contains ### also begining and end.
        return null;
    }

    if (readableBytes >= 5) {
        boolean messageStart = false;
        int indexMessageBegin;
        for (int i = 0; i < readableBytes; i++) {
            int readerIndex = buffer.readerIndex() + i;
            if (buffer.getByte(readerIndex) == 35) { // Message begin.
                messageStart = true;
                indexMessageBegin = i;
            }
            if (messageStart) {
                if (buffer.getByte(i) == 35 && buffer.getByte(i + 1) == 35) {
                    messageStart = false;
                    // when reading the message I want to cut it out from the stream
                    byte[] decoded = new byte[0x00 + i];
                }
            }

        }
    }

    return null;
}

0 个答案:

没有答案