客户端服务器通信Android

时间:2015-08-10 10:37:47

标签: android client server messages

我们如何向Android中的特定格式的服务器发送请求,例如

[RequestID-1byte] [sourceID-1byte] [datalen-4byte] [数据部分]

2 个答案:

答案 0 :(得分:0)

我不确定,但我认为您可以使用Volley Library执行类似的操作:

StringRequest mStringRequest = new StringRequest(Request.Method.POST, URL_VALIDATE, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            // code for response here
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            // code for error response here
        }
    }) {
        @Override
        protected Map<String, Byte> getParams() {
            Map<String, Byte> params = new HashMap<>();
            // the POST parameters:
            params.put("RequestID", byte1);
            params.put("sourceID", byte2);
            params.put("datalen", byte3);
            return params;
        }
    };

    Volley.newRequestQueue(this).add(mStringRequest);

希望它有所帮助!

答案 1 :(得分:0)

使用服务器 - 客户端套接字编程?

我正在编写示例代码。

array = {2,1,3} 
count_array = {0,1,1,1}
result_array = {0,1,2,3}
rank_array = {1,0,2} //rank_array[i] = result_array[array[i]] - 1

和套接字I / O

public class Packet {

    private byte requestID;
    private byte sourceID;
    private byte[] data;

    public Packet(byte requestID, byte sourceID, byte[] data) {
        this.requestID = requestID;
        this.sourceID = sourceID;
        // TODO: add exception handling for data length > 65535, data length more 4byte
        this.data = data;
    }

    public byte[] getData() throws IOException{

        ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
        byteStream.write(requestID);
        byteStream.write(sourceID);

        if(data.length<0xff) // if data length < 255, data byte is 2
            byteStream.write(0);
        byteStream.write((short)data.length);
        byteStream.write(data);
        byteStream.close();
        return byteStream.toByteArray();
    }
}