package com.warewms.socket;

import com.fdd.protobuf.InfoProto;
import com.google.protobuf.ByteString;

import java.io.DataInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

/**
 * 服务端客户消息处理线程类
 */
public class SocketServerClientHandler extends Thread {

    //每个消息通过Socket进行传输
    private Socket clientConnectSocket;

    public SocketServerClientHandler(Socket clientConnectSocket) {
        this.clientConnectSocket = clientConnectSocket;
    }

    @Override
    public void run() {
        try {
            InputStream is = clientConnectSocket.getInputStream();
            OutputStream os = clientConnectSocket.getOutputStream();
            while (true) {
                DataInputStream dis = new DataInputStream(is);
                //读取长度
                int lenData = dis.readInt();

                InfoProto.imu imu = InfoProto.imu.parseFrom(ByteString.readFrom(is));
                if (null != imu) {
                    System.out.println("server received data:\n" + imu.toString());

                    imu = InfoProto.imu.newBuilder().setTimestampUs(1000).setVid(999) .build();
                    os.write(imu.toByteArray());
                    os.flush();
                }
            }

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