java 调用tcp接口
时间: 2023-09-26 21:06:54 浏览: 52
Java 可以通过 Socket 类来调用 TCP 接口。下面是一个简单的示例:
```java
import java.io.*;
import java.net.*;
public class TCPClient {
public static void main(String[] args) throws Exception {
String serverIpAddress = "127.0.0.1";
int serverPort = 12345;
Socket socket = new Socket(serverIpAddress, serverPort);
OutputStream outputStream = socket.getOutputStream();
PrintWriter writer = new PrintWriter(outputStream, true);
writer.println("Hello, server!");
InputStream inputStream = socket.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String response = reader.readLine();
System.out.println("Server response: " + response);
socket.close();
}
}
```
在这个示例中,我们通过 Socket 类创建了一个 TCP 连接,并向服务器发送了一条消息。服务器接收到消息后,返回了一条响应,客户端读取并输出了这个响应,并关闭了连接。
你需要将 `serverIpAddress` 和 `serverPort` 替换为你要连接的 TCP 接口的 IP 地址和端口号。同时,你需要根据具体的接口协议,确定发送的消息格式和解析响应的方式。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![-](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://img-home.csdnimg.cn/images/20210720083327.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)