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
|
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <poll.h>
#include <pthread.h>
#include <string.h>
#define SA(ptr) ((struct sockaddr *)(ptr))
void *recv_data_c(void *arg) {
int socketfd = *(int *)arg;
while(1){
char buffer[30000]={0};
recv(socketfd, buffer, 30000, 0);
printf("%s\n ",buffer);
}
}
int main(int argc, char *argv[]){
if (argc<2){
fprintf(stderr, "arg1 must be set for port\n");
exit(-1);
}
int port = atoi(argv[1]);
if (port == 0) {
fprintf(stderr, "port must not be 0\n");
exit(-1);
}
int socketfd = socket(AF_INET, SOCK_STREAM, 0);
struct sockaddr_in address = {0};
address.sin_family = AF_INET;
address.sin_port = htons(port);
address.sin_addr.s_addr = inet_addr("127.0.0.1");
int con_err=connect(socketfd, SA(&address), sizeof(address));
if (con_err<0){
printf("connect error %d\n",con_err);
perror("socketfd error");
exit(-1);
}
send(socketfd, "connected", strlen("connected"), 0);
char *name = NULL;
size_t nameSize = 0;
printf("please enter your name\n");
ssize_t nameCount = getline(&name, &nameSize, stdin);
name[nameCount-1]=0; //gets rid of newline
char *line = NULL;
size_t lineSize = 0;
pthread_t id;
pthread_create(&id, NULL, recv_data_c, &socketfd);
char send_buf[30000];
while(1){
ssize_t charCount = getline(&line, &lineSize, stdin);
line[charCount-1]=0; //gets rid of newline
sprintf(send_buf, "%s:%s", name, line);
if(charCount>0){
if(strcmp(line,"exit")==0){
break;
} else {
send(socketfd, send_buf, strlen(send_buf), 0);
}
}
}
close(socketfd);
return 0;
}
|