java与c 通信_Java与C之间的socket通信 建立长链接
时间: 2024-02-21 09:59:54 浏览: 27
要建立长连接,需要在Java和C端的代码中进行一些修改:
Java端代码:
```java
import java.net.*;
import java.io.*;
public class JavaSocket {
public static void main(String[] args) {
try {
Socket socket = new Socket("localhost", 8888);
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String inputLine, outputLine;
outputLine = "Hello from Java!";
out.println(outputLine);
while ((inputLine = in.readLine()) != null) {
System.out.println("Received from C: " + inputLine);
outputLine = "Hello from Java again!";
out.println(outputLine);
}
out.close();
in.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
C语言端代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define PORT 8888
#define MAXLINE 1024
int main() {
int sockfd;
struct sockaddr_in servaddr;
char sendline[MAXLINE], recvline[MAXLINE];
sockfd = socket(AF_INET, SOCK_STREAM, 0);
bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = inet_addr("127.0.0.1");
servaddr.sin_port = htons(PORT);
connect(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr));
while (1) {
if (recv(sockfd, recvline, MAXLINE, 0) == 0) {
printf("Server terminated prematurely\n");
exit(1);
}
printf("Received from Java: %s", recvline);
printf("Enter message to send to Java: ");
fgets(sendline, MAXLINE, stdin);
send(sockfd, sendline, strlen(sendline), 0);
}
close(sockfd);
exit(0);
}
```
在Java端代码中,我们将while循环放在了try语句块之外,这样就可以在C语言端关闭socket连接后继续向Java端发送消息。在C语言端代码中,我们将while循环改为了一个无限循环,每次接收Java端的消息后,再等待用户输入要发送给Java端的消息。这样就可以实现长连接了。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.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)
![](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)