-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchat_clnt.c
93 lines (79 loc) · 1.89 KB
/
chat_clnt.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
89
90
91
92
93
#include <stdio.h>
#include <pthread.h>
#include <string.h>
#include <sys/socket.h>
#include <stdlib.h>
#include <unistd.h>
#include <arpa/inet.h>
#define BUF_SIZE 100
#define NAME_SIZE 20
void * send_msg(void *arg);
void * recv_msg(void *arg);
void error_handling(char *msg);
char name[NAME_SIZE] = "[DEFAULT]";
char msg[BUF_SIZE];
int main(int argc, char const *argv[])
{
int sock;
struct sockaddr_in serv_addr;
pthread_t snd_thread, rcv_thread;
void * thread_return;
if (argc != 4)
{
printf("Usage: %s <IP> <PORT> <name> \n", argv[0]);
exit(1);
}
sprintf(name, "[%s]",argv[3]);
sock = socket(PF_INET, SOCK_STREAM, 0);
memset(&serv_addr, 0, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
if(!inet_aton(argv[1],&serv_addr.sin_addr))
error_handling("convert err");
serv_addr.sin_port = htons(atoi(argv[2]));
if(connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) == -1)
error_handling("connect err");
pthread_create(&snd_thread, NULL, send_msg, (void*)&sock);
pthread_create(&rcv_thread, NULL, recv_msg, (void*)&sock);
pthread_join(snd_thread, &thread_return);
pthread_join(rcv_thread, &thread_return);
close(sock);
return 0;
}
void * send_msg(void * arg)//send thread main
{
int sock = *((int *)arg);
char name_msg[NAME_SIZE+BUF_SIZE];
while(1)
{
fgets(msg, BUF_SIZE, stdin);
if(!strcmp(msg,"q\n") || !strcmp(msg,"Q\n"))
{
close(sock);
exit(0);
}
sprintf(name_msg, "%s %s",name, msg);
write(sock, name_msg,strlen(name_msg));
}
return NULL;
}
void *recv_msg(void *arg)
{
int sock = *((int*)arg);
char name_msg[NAME_SIZE+BUF_SIZE];
int str_len;
while(1)
{
str_len = read(sock,name_msg,NAME_SIZE+BUF_SIZE-1);
if(str_len == -1)
return (void*)-1;
name_msg[str_len] = 0;
fputs(name_msg,stdout);
}
return NULL;
}
void error_handling(char *message)
{
fputs(message, stderr);
fputc('\n', stderr);
exit(1);
}