Socket通讯传输字符串和对象的解决方案——转换流和JSON

Socket通讯传输字符串和对象的解决方案——转换流和JSON

传输字符串

案例

/**
 * 发送字符串
 */
private void sendString(String judgment) throws IOException {
    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "utf-8"));
    writer.write(judgment + "\n");
    writer.flush();
}

/**
 * 接收字符串
 *
 * @return
 */
private String receiveString() throws IOException {
    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "utf-8"));
    return reader.readLine();
}

传输对象

如何使用Socket通讯传输对象(思路)

经过测试序列化不行(不知道是不是我方法的问题),刚好想到了JSON格式类型确实是字符串。
Socket通讯是可以使用io的转换流传输字符串

传输对象流程

Java对象—jackson—>JSON格式的字符串—转换流—>字节流——>发送

使用JSON解决对象传输

jackson教程——Java 最佳 JSON 解析器

案例

/**
 * 发送java对象
 */
private <T> void sendObject(T t) throws IOException {
    // 使用 ObjectMapper 类将其转换成 JSON 格式的数据
    this.sendString(new ObjectMapper().writeValueAsString(t));
}

/**
 * 发送字符串
 */
private void sendString(String judgment) throws IOException {
    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "utf-8"));
    writer.write(judgment + "\n");
    writer.flush();
}

/**
 * 接收对象
 */
private <T> T receiveObject(Class<? extends T> clazz) throws IOException {
    return new ObjectMapper().readValue(this.receiveString(), clazz);
}

/**
 * 接收字符串
 *
 * @return
 */
private String receiveString() throws IOException {
    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "utf-8"));
    return reader.readLine();
}