springboot发送tcp请求
时间: 2023-12-19 20:07:13 浏览: 132
可以使用Java自带的Socket类或者第三方库Netty来发送TCP请求。以下是使用Socket类发送TCP请求的示例代码:
```java
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
public class TcpClient {
public static void main(String[] args) {
String host = "localhost";
int port = 8080;
try {
Socket socket = new Socket(host, port);
OutputStream outputStream = socket.getOutputStream();
String message = "Hello, TCP server!";
outputStream.write(message.getBytes());
outputStream.flush();
InputStream inputStream = socket.getInputStream();
byte[] buffer = new byte[1024];
int len = inputStream.read(buffer);
String response = new String(buffer, 0, len);
System.out.println("Server response: " + response);
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
在Spring Boot中,可以将TCP请求封装为一个服务或者组件,然后在需要的地方注入调用。例如:
```java
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
@Component
public class TcpClient {
private final String host = "localhost";
private final int port = 8080;
public String send(String message) {
try {
Socket socket = new Socket(host, port);
OutputStream outputStream = socket.getOutputStream();
outputStream.write(message.getBytes());
outputStream.flush();
InputStream inputStream = socket.getInputStream();
byte[] buffer = new byte[1024];
int len = inputStream.read(buffer);
String response = new String(buffer, 0, len);
socket.close();
return response;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
```
然后在需要发送TCP请求的地方,可以通过注入TcpClient服务来发送请求:
```java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class MyController {
@Autowired
private TcpClient tcpClient;
@GetMapping("/tcp")
public String sendTcpRequest() {
String message = "Hello, TCP server!";
String response = tcpClient.send(message);
return "Server response: " + response;
}
}
```
当访问 /tcp 接口时,会发送 TCP 请求并返回响应结果。
阅读全文