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();
}
/**
* 斷開連接
* @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)文章
mybatis3使用@Select等注解實(shí)現(xiàn)增刪改查操作
這篇文章主要介紹了mybatis3使用@Select等注解實(shí)現(xiàn)增刪改查操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-11-11
Apache Calcite進(jìn)行SQL解析(java代碼實(shí)例)
Calcite是一款開源SQL解析工具, 可以將各種SQL語句解析成抽象語法樹AST(Abstract Syntax Tree), 之后通過操作AST就可以把SQL中所要表達(dá)的算法與關(guān)系體現(xiàn)在具體代碼之中,今天通過代碼實(shí)例給大家介紹Apache Calcite進(jìn)行SQL解析問題,感興趣的朋友一起看看吧2022-01-01
Spring AOP如何自定義注解實(shí)現(xiàn)審計(jì)或日志記錄(完整代碼)
這篇文章主要介紹了Spring AOP如何自定義注解實(shí)現(xiàn)審計(jì)或日志記錄(完整代碼),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-12-12
Spring中的@Conditional注解實(shí)現(xiàn)分析
這篇文章主要介紹了Spring中的@Conditional注解實(shí)現(xiàn)分析, @Conditional是Spring 4出現(xiàn)的注解,但是真正露出價(jià)值的是Spring Boot的擴(kuò)展@ConditionalOnBean等,需要的朋友可以參考下2023-12-12
簡(jiǎn)單的用java實(shí)現(xiàn)讀/寫文本文件的示例
同時(shí)也展示了如果從輸入流中讀出來內(nèi)容寫入輸出流中(僅限文本流) 三個(gè)例子可以獨(dú)立存在,所以根據(jù)需要只看其中一個(gè)就行了。2008-07-07
JDK動(dòng)態(tài)代理過程原理及手寫實(shí)現(xiàn)詳解
這篇文章主要為大家介紹了JDK動(dòng)態(tài)代理過程原理及手寫實(shí)現(xiàn)詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-09-09

