Skip to content
徐昊 edited this page Nov 10, 2018 · 3 revisions
  • Define the data structure to be sent
public class TestSendData implements ISendable {
	private String str = "";

    public TestSendData() {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("cmd", 14);
            jsonObject.put("data", "{x:2,y:1}");
            str = jsonObject.toString();
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    public byte[] parse() {
    	//Build the byte array according to the server's parsing rules
        byte[] payload = str.getBytes(Charset.defaultCharset());
        //4 is package header fixed length and payload length
        ByteBuffer bb = ByteBuffer.allocate(4 + payload.length);
        bb.order(ByteOrder.BIG_ENDIAN);
        bb.putInt(payload.length);
        bb.put(payload);
        return bb.array();
    }
}
  • Send data through the manager
private IConnectionManager mManager;
//...Omit the connection and set the associated code for the callback...
@Override
public void onSocketConnectionSuccess(ConnectionInfo info, String action) {
     //Chain programming call
     OkSocket.open(info)
     	.send(new TestSendData());
}