SpringBoot實(shí)現(xiàn)TCP連接并進(jìn)行數(shù)據(jù)互傳的方法
application.yml
tcp:
server:
ip: 192.168.173.25
port: 20140
server:
port: 6000TcpDataSenderController
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();
}
/**
* 斷開(kāi)連接
* @return
*/
@GetMapping("/disconnect")
public boolean disconnect() {
return tcpClientUtil.disconnect();
}
/**
* 發(fā)送數(shù)據(jù)
* @param data
* @return
*/
@GetMapping("/send")
public boolean send(@RequestParam("data") String data) {
return tcpClientUtil.sendData(data);
}
/**
* 發(fā)送數(shù)據(jù)(有返回?cái)?shù)據(jù))
* @param data
* @return
*/
@GetMapping("/sendData")
public String sendDataToServer(@RequestParam("data") String data) {
return tcpClientUtil.sendDataToServer(data);
}
/**
* 獲取連接狀態(tài)
* @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()));
// 發(fā)送數(shù)據(jù)到TCP服務(wù)器
outputStream.write(data.getBytes(StandardCharsets.UTF_8));
outputStream.flush();
// 讀取服務(wù)器返回的數(shù)據(jù)(如果需要處理返回內(nèi)容的話)
String response = reader.readLine();
if (response!= null) {
logger.info("從TCP服務(wù)器接收到的響應(yīng): {}", response);
}
return response;
}
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
lock.unlock();
}
return null;
}
public boolean isConnected() {
return isConnected;
}
}到此這篇關(guān)于SpringBoot實(shí)現(xiàn)TCP連接并進(jìn)行數(shù)據(jù)互傳的文章就介紹到這了,更多相關(guān)Docker翻譯組件Deepl使用內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
解決mysql字符串類(lèi)型的數(shù)字排序出錯(cuò):cast(year as signed)
這篇文章主要介紹了解決mysql字符串類(lèi)型的數(shù)字排序出錯(cuò)問(wèn)題 :cast(year as signed),如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-08-08
Spring?Security入門(mén)到深入實(shí)戰(zhàn)步驟詳解
小明通過(guò)學(xué)習(xí)SpringSecurity,成功為自己的攝影網(wǎng)站添加了完整的登錄認(rèn)證鑒權(quán)功能,包括自定義用戶存儲(chǔ)、權(quán)限控制、自定義登錄頁(yè)、JWT集成以及OAuth2第三方登錄,并且對(duì)SpringSecurity有了深入的理解和認(rèn)識(shí),喜歡的朋友跟隨小編一起學(xué)習(xí)吧2025-11-11
Spring中使用JSR303請(qǐng)求約束判空的實(shí)現(xiàn)
這篇文章主要介紹了Spring中使用JSR303請(qǐng)求約束判空的實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-12-12
Hadoop環(huán)境配置之hive環(huán)境配置詳解
這篇文章主要介紹了Hadoop環(huán)境配置之hive環(huán)境配置,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-12-12
SpringBoot設(shè)置動(dòng)態(tài)定時(shí)任務(wù)的方法詳解
這篇文章主要為大家詳細(xì)介紹了SpringBoot設(shè)置動(dòng)態(tài)定時(shí)任務(wù)的方法,文中的示例代碼講解詳細(xì),對(duì)我們學(xué)習(xí)有一定的參考價(jià)值,需要的可以參考一下2022-06-06
一文詳解Java Netty中的Constant類(lèi)
這篇文章主要介紹了Constants類(lèi)即常量類(lèi)是將一些常用的變量集合到一個(gè)地方的類(lèi),文中有詳細(xì)的代碼示例,感興趣的同學(xué)可以參考一下2023-05-05
Java swing實(shí)現(xiàn)的計(jì)算器功能完整實(shí)例
這篇文章主要介紹了Java swing實(shí)現(xiàn)的計(jì)算器功能,結(jié)合完整實(shí)例形式分析了java基于swing組件實(shí)現(xiàn)計(jì)算器布局與運(yùn)算功能的具體操作技巧,需要的朋友可以參考下2017-12-12

