-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathclient.cpp
More file actions
119 lines (113 loc) · 2.86 KB
/
Copy pathclient.cpp
File metadata and controls
119 lines (113 loc) · 2.86 KB
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
#include <vector>
#include <pthread.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include "strtools.h"
#define MAX_LINE_LEN 4096
#define __DEBUG__ 0
#define DEBUG(argv, format...)do{\
if (__DEBUG__){\
fprintf(stderr, argv, ##format);\
}\
}while(0)
using std::vector;
void *recv(void *arg)
{
int sockfd = *(int *)arg;
int n = 0;
char recv_line[MAX_LINE_LEN];
vector<char *> list;
while (true)
{
n = recv(sockfd, recv_line, MAX_LINE_LEN, 0);
if (n <= 0)
{
fprintf(stderr, "recieve from server failed!\n");
break;
}
recv_line[n] = 0;
DEBUG("revline:%s\n", recv_line);
split(list, recv_line, 30);
DEBUG("recieve bytes[%d] records[%d]\n", n, static_cast<int>(list.size()));
for(int i = 0; i < list.size(); ++i)
{
if (strlen(list[i]) > 0)
{
printf(">>%s\n", list[i]);
fflush(stdout);
}
}
}
}
void *send(void *arg)
{
int sockfd = *static_cast<int *>(arg);
int n = 0;
char sendline[MAX_LINE_LEN];
while (true)
{
fgets(sendline, MAX_LINE_LEN, stdin);
sendline[strlen(sendline) - 1] = 0;
if (strcmp(sendline, "quit") == 0)
{
break;
}
if (send(sockfd, sendline, strlen(sendline), 0) < 0)
{
printf("send msg error: %s(errno: %d)\n", strerror(errno), errno);
break;
}
}
}
int initSock(char *ip, int port)
{
struct sockaddr_in servaddr;
int sockfd = socket(AF_INET, SOCK_STREAM, 0);
DEBUG("sockfd: %d\n", sockfd);
if (sockfd < 0)
{
printf("create socket error: %s(errno: %d\n)\n", strerror(errno), errno);
return -1;
}
memset(&servaddr, 0, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(port);
if (inet_pton(AF_INET, ip, &servaddr.sin_addr) <= 0)
{
printf("inet_pton error for %s\n", ip);
return -1;
}
if (connect(sockfd, (struct sockaddr*)&servaddr, sizeof(servaddr)) < 0)
{
printf("connect error: %s(errno: %d)\n", strerror(errno), errno);
return -1;
}
return sockfd;
}
int main(int argc, char *argv[])
{
int sockfd;
if (argc != 3)
{
printf("usage: %s <ipaddress> <port>\n", argv[0]);
return 1;
}
if ((sockfd = initSock(argv[1], atoi(argv[2]))) < 0)
{
return 1;
}
DEBUG("initSock finished! sockfd[%d]\n", sockfd);
pthread_t thread_recv, thread_send;
pthread_create(&thread_recv, NULL, recv, &sockfd);
pthread_create(&thread_send, NULL, send, &sockfd);
pthread_join(thread_send, NULL);
close(sockfd);
return 0;
}