用C++写一个点对点的通信系统
时间: 2023-05-14 20:04:57 浏览: 163
好的,我可以为您提供一个基于C语言的点对点通信系统的代码示例:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#define PORT 8888
int main(int argc, char *argv[]) {
int sockfd, ret;
struct sockaddr_in serverAddr, clientAddr;
char buffer[1024];
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0) {
printf("Error creating socket!\n");
exit(1);
}
printf("Socket created...\n");
memset(&serverAddr, 0, sizeof(serverAddr));
serverAddr.sin_family = AF_INET;
serverAddr.sin_addr.s_addr = INADDR_ANY;
serverAddr.sin_port = htons(PORT);
ret = bind(sockfd, (struct sockaddr*)&serverAddr, sizeof(serverAddr));
if (ret < 0) {
printf("Error binding!\n");
exit(1);
}
printf("Binding done...\n");
printf("Listening for incoming connections...\n");
listen(sockfd, 10);
while (1) {
socklen_t len = sizeof(clientAddr);
int clientfd = accept(sockfd, (struct sockaddr*)&clientAddr, &len);
if (clientfd < 0) {
printf("Error accepting connection!\n");
exit(1);
}
printf("Connection accepted...\n");
memset(buffer, 0, sizeof(buffer));
printf("Enter your message: ");
fgets(buffer, sizeof(buffer), stdin);
ret = send(clientfd, buffer, strlen(buffer), 0);
if (ret < 0) {
printf("Error sending message!\n");
exit(1);
}
printf("Message sent to client...\n");
close(clientfd);
}
return 0;
}
```
这个代码示例实现了一个简单的点对点通信系统,使用了TCP协议进行通信。您可以根据需要进行修改和扩展。
阅读全文