Java客户端套接字读取超时

时间:2017-06-29 20:16:00

标签: java sockets

通过套接字消耗远程API的实际开发的Web应用程序。此API返回一个字符串响应,我的问题是在读取数据时获取成功消息和超时消息错误的相同响应。

服务器配置为10000秒并抛出超时消息。我不知道来自服务器的代码我只是开发客户端来消费它。

下面是我从套接字响应中读取数据的代码。

这种服务方式:

public String activateSale(final OSBDTO osbDto) throws Exception {

    Socket conn = socketConfig(HOST, PORT);
    BufferedOutputStream bos = new BufferedOutputStream(conn.getOutputStream());
    this.repository.sendDataSocket(MessageUtil.mountAuthenticationMsg(osbDto), conn, bos);


    BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());
    String receivedData = this.repository.readMessage(conn, bis, bos);
    closeConnection(conn);

    if (OsbUtils.getStatusCodeMsg(receivedData).equals(MessageStatusEnum.SUCCESS.getStatusCode())) {

        conn = socketConfig(HOST, PORT);

        bos = new BufferedOutputStream(conn.getOutputStream());
        this.repository.sendDataSocket(MessageUtil.mountConfigurationSeriesMsg(osbDto), conn, bos);

        bis = new BufferedInputStream(conn.getInputStream());
        receivedData = this.repository.readMessage(conn, bis, bos);
        closeConnection(conn);

    } else {

        throw new Exception(MessageStatusEnum.getStatusDesc(OsbUtils.getStatusCodeMsg(receivedData)));
    }

    return receivedData;
}

这种发送和读取方法:

@Override
public void sendDataSocket(final String msg, final Socket conn, final BufferedOutputStream bos) throws Exception {

    try {

        bos.write(msg.getBytes());
        bos.flush();

    } catch (Exception e) {
        LOGGER.error("Error to send message." + e.getMessage());
        throw e;
    }

}


@Override
public String readMessage(final Socket conn, final BufferedInputStream bis, final BufferedOutputStream bos) throws IOException {

    byte[] bufferSize = new byte[1024 * 1024];
    int data ;
    StringBuilder builder = new StringBuilder();
    while ((data = bis.read(bufferSize)) != -1) {
        builder.append(new String(bufferSize, 0, data));
    }
    bis.close();
    bos.close();
    return builder.toString();
}

0 个答案:

没有答案