SpringBoot实现TCP连接并进行数据互传的方法

 更新时间:2025年01月10日 14:56:38   作者:liaozk_c  
本文详细介绍了微服务架构中的翻译组件使用场景,以及多种开源翻译组件的解决方案,文中分析了国内外多个翻译服务如百度翻译、谷歌翻译等,以及如何在微服务项目中集成这些翻译组件,感兴趣的朋友跟随小编一起看看吧

application.yml

tcp:
  server:
    ip: 192.168.173.25
    port: 20140
server:
  port: 6000

TcpDataSenderController

import com.example.tcpclient.utils.TcpClientUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
/**
 * tcp接口
 */
@RestController
@RequestMapping("/tcp")
public class TcpDataSenderController {
    private final TcpClientUtil tcpClientUtil;
    @Autowired
    public TcpDataSenderController(TcpClientUtil tcpClientUtil) {
        this.tcpClientUtil = tcpClientUtil;
    }
    /**
     * 连接
     * @return
     */
    @GetMapping("/connect")
    public boolean connect() {
        return tcpClientUtil.connect();
    }
    /**
     * 断开连接
     * @return
     */
    @GetMapping("/disconnect")
    public boolean disconnect() {
        return tcpClientUtil.disconnect();
    }
    /**
     * 发送数据
     * @param data
     * @return
     */
    @GetMapping("/send")
    public boolean send(@RequestParam("data") String data) {
        return tcpClientUtil.sendData(data);
    }
    /**
     * 发送数据(有返回数据)
     * @param data
     * @return
     */
    @GetMapping("/sendData")
    public String sendDataToServer(@RequestParam("data") String data) {
        return tcpClientUtil.sendDataToServer(data);
    }
    /**
     * 获取连接状态
     * @return
     */
    @GetMapping("/status")
    public boolean status() {
        return tcpClientUtil.isConnected();
    }
}

TcpClientUtil

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
@Component
public class TcpClientUtil {
    private static final Logger logger = LoggerFactory.getLogger(TcpClientUtil.class);
    @Value("${tcp.server.ip}")
    private String tcpServerIp;
    @Value("${tcp.server.port}")
    private int tcpServerPort;
    private Socket socket;
    private OutputStream outputStream;
    private Lock lock = new ReentrantLock();
    private boolean isConnected = false;
    public boolean connect() {
        lock.lock();
        try {
            if (!isConnected) {
                socket = new Socket(tcpServerIp, tcpServerPort);
                outputStream = socket.getOutputStream();
                isConnected = true;
                return true;
            }
            return false;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            lock.unlock();
        }
    }
    public boolean disconnect() {
        lock.lock();
        try {
            if (isConnected) {
                if (outputStream != null) {
                    try {
                        outputStream.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                if (socket != null) {
                    try {
                        socket.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                isConnected = false;
                return true;
            }
            return false;
        } finally {
            lock.unlock();
        }
    }
    public boolean sendData(String data) {
        lock.lock();
        try {
            if (isConnected) {
                byte[] bytes = data.getBytes();
                outputStream.write(bytes);
                outputStream.flush();
                return true;
            }
            return false;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            lock.unlock();
        }
    }
    public String sendDataToServer(String data) {
        lock.lock();
        try {
            if (isConnected) {
                BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                // 发送数据到TCP服务器
                outputStream.write(data.getBytes(StandardCharsets.UTF_8));
                outputStream.flush();
                // 读取服务器返回的数据(如果需要处理返回内容的话)
                String response = reader.readLine();
                if (response!= null) {
                    logger.info("从TCP服务器接收到的响应: {}", response);
                }
                return response;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            lock.unlock();
        }
        return null;
    }
    public boolean isConnected() {
        return isConnected;
    }
}

到此这篇关于SpringBoot实现TCP连接并进行数据互传的文章就介绍到这了,更多相关Docker翻译组件Deepl使用内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • 解决mysql字符串类型的数字排序出错:cast(year as signed)

    解决mysql字符串类型的数字排序出错:cast(year as signed)

    这篇文章主要介绍了解决mysql字符串类型的数字排序出错问题 :cast(year as signed),如有错误或未考虑完全的地方,望不吝赐教
    2023-08-08
  • Spring Security入门到深入实战步骤详解

    Spring Security入门到深入实战步骤详解

    小明通过学习SpringSecurity,成功为自己的摄影网站添加了完整的登录认证鉴权功能,包括自定义用户存储、权限控制、自定义登录页、JWT集成以及OAuth2第三方登录,并且对SpringSecurity有了深入的理解和认识,喜欢的朋友跟随小编一起学习吧
    2025-11-11
  • Spring中使用JSR303请求约束判空的实现

    Spring中使用JSR303请求约束判空的实现

    这篇文章主要介绍了Spring中使用JSR303请求约束判空的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-12-12
  • MyBatis 引入映射器的方法

    MyBatis 引入映射器的方法

    本文通过实例代码给大家分享mybatis 引入映射器的方法,非常不错,具有参考借鉴价值,需要的朋友参考下吧
    2017-09-09
  • Hadoop环境配置之hive环境配置详解

    Hadoop环境配置之hive环境配置详解

    这篇文章主要介绍了Hadoop环境配置之hive环境配置,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2021-12-12
  • SpringBoot设置动态定时任务的方法详解

    SpringBoot设置动态定时任务的方法详解

    这篇文章主要为大家详细介绍了SpringBoot设置动态定时任务的方法,文中的示例代码讲解详细,对我们学习有一定的参考价值,需要的可以参考一下
    2022-06-06
  • 一文详解Java Netty中的Constant类

    一文详解Java Netty中的Constant类

    这篇文章主要介绍了Constants类即常量类是将一些常用的变量集合到一个地方的类,文中有详细的代码示例,感兴趣的同学可以参考一下
    2023-05-05
  • springboot之如何获取请求ip方法

    springboot之如何获取请求ip方法

    这篇文章主要介绍了springboot之如何获取请求ip方法,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2023-07-07
  • java判断ftp目录是否存在的方法

    java判断ftp目录是否存在的方法

    这篇文章主要为大家详细介绍了java判断ftp目录是否存在的方法,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2017-04-04
  • Java swing实现的计算器功能完整实例

    Java swing实现的计算器功能完整实例

    这篇文章主要介绍了Java swing实现的计算器功能,结合完整实例形式分析了java基于swing组件实现计算器布局与运算功能的具体操作技巧,需要的朋友可以参考下
    2017-12-12

最新评论