-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathclient.c
88 lines (71 loc) · 1.82 KB
/
client.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <unistd.h>
#include <pthread.h>
#include "global.h"
static char buf[MAX_BUF_LEN];
void *recv_thrd(void *arg); /* 客户端接收信息线程 */
int main(int argc, char *argv[])
{
struct sockaddr_in srv;
int sock_fd, chk;
pthread_t tid;
pthread_attr_t attr;
if (argc != 3)
{
printf("usage: %s ipaddr port", argv[0]);
return -1;
}
if ((sock_fd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
{
printf("socket error!");
return -1;
}
bzero(&srv, sizeof(srv));
srv.sin_family = AF_INET;
srv.sin_port = htons(atoi(argv[2])); /* port */
chk = inet_pton(AF_INET, argv[1], &srv.sin_addr); /* x.x.x.x to network ipaddr */
if (chk < 0)
{
printf("illegal ip address!");
return -1;
}
chk = connect(sock_fd, (struct sockaddr *)&srv, sizeof(srv));
if (chk < 0)
{
printf("connect error!");
return -1;
}
/* 接收消息的线程 */
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
chk = pthread_create(&tid, &attr, &recv_thrd, (void *)sock_fd); /* 接收线程 */
if (chk)
{
printf("create thread error!");
return -1;
}
while (fgets(buf, sizeof(buf), stdin) != NULL)
{
send(sock_fd, buf, sizeof(buf), 0);
}
close(sock_fd);
chk = pthread_join(tid, NULL);
pthread_attr_destroy(&attr);
return 0;
}
void *recv_thrd(void *arg) /* 接收线程 */
{
int sock_fd = (int)arg;
int rec_bytes;
while ((rec_bytes = recv(sock_fd, buf, sizeof(buf), 0)) > 0)
{
buf[rec_bytes] = '\0';
printf("\r%s", buf);
}
pthread_exit(NULL);
}