aboutsummaryrefslogtreecommitdiffstats
path: root/testClient.c
diff options
context:
space:
mode:
Diffstat (limited to 'testClient.c')
-rw-r--r--testClient.c97
1 files changed, 97 insertions, 0 deletions
diff --git a/testClient.c b/testClient.c
new file mode 100644
index 0000000..bbd2529
--- /dev/null
+++ b/testClient.c
@@ -0,0 +1,97 @@
1// 编写一段C程序,使用pthread创建两个线程
2// 发送线程将数据发送到127.0.0.1的5001端口,每0.5s一次
3// 接收线程接收127.0.0.1的5001端口的数据并打印
4
5#include <arpa/inet.h>
6#include <errno.h>
7#include <fcntl.h>
8#include <netinet/in.h>
9#include <pthread.h>
10#include <stdbool.h>
11#include <stdio.h>
12#include <stdlib.h>
13#include <string.h>
14#include <sys/socket.h>
15#include <termios.h>
16#include <unistd.h>
17
18pthread_t udpSend, udpRecv;
19pthread_mutex_t mutex;
20int port = 5001;
21char clientIP[20] = "127.0.0.1";
22
23void udpSenderThread() {
24 struct sockaddr_in serverAddr;
25 int sockfd = -1;
26
27 // 创建UDP套接字
28 if ((sockfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1) {
29 fprintf(stderr, "Error: Failed to create socket\n");
30 return;
31 }
32
33 memset((char *)&serverAddr, 0, sizeof(serverAddr));
34 serverAddr.sin_family = AF_INET;
35 serverAddr.sin_port = htons(port);
36 serverAddr.sin_addr.s_addr = inet_addr(clientIP);
37
38 while (1) {
39 char values[100] = {0};
40 // strcpy(values, "Hello, world!");
41 pthread_mutex_lock(&mutex);
42 printf("Input the data you want to send: ");
43 scanf("%s", values);
44 pthread_mutex_unlock(&mutex);
45 sendto(sockfd, values, strlen(values), 0,
46 (struct sockaddr *)&serverAddr, sizeof(serverAddr));
47 // printf("Send: %s\n", values);
48 sleep(1);
49 }
50}
51
52void udpReceiverThread() {
53 int sockfd = -1;
54 struct sockaddr_in serverAddr;
55 struct sockaddr_in clientAddr;
56 socklen_t clientAddrLen = sizeof(clientAddr);
57 char buffer[1024] = {0};
58
59 // 创建UDP套接字
60 if ((sockfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1) {
61 fprintf(stderr, "Error: Failed to create socket\n");
62 return;
63 }
64
65 memset((char *)&serverAddr, 0, sizeof(serverAddr));
66 serverAddr.sin_family = AF_INET;
67 serverAddr.sin_port = htons(port - 1);
68 serverAddr.sin_addr.s_addr = htonl(INADDR_ANY);
69
70 if (bind(sockfd, (struct sockaddr *)&serverAddr, sizeof(serverAddr)) ==
71 -1) {
72 fprintf(stderr, "Error: Failed to bind socket\n");
73 close(sockfd);
74 return;
75 }
76
77 while (1) {
78 pthread_mutex_lock(&mutex);
79 int len = recvfrom(sockfd, buffer, 1024, 0,
80 (struct sockaddr *)&clientAddr, &clientAddrLen);
81 pthread_mutex_unlock(&mutex);
82 if (len == -1) {
83 fprintf(stderr, "Error: Failed to receive data\n");
84 close(sockfd);
85 return;
86 }
87 buffer[len] = '\0';
88 printf("Received: %s\n", buffer);
89 }
90}
91
92int main() {
93 pthread_create(&udpSend, NULL, udpSenderThread, NULL);
94 // pthread_create(&udpRecv, NULL, udpReceiverThread, NULL);
95 pthread_join(udpSend, NULL);
96 // pthread_join(udpRecv, NULL);
97} \ No newline at end of file