-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy path1.c
62 lines (59 loc) · 1.52 KB
/
1.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
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <pthread.h>
struct Pipe {
int fd_send;
int fd_recv;
};
void *handle_chat(void *data) {
struct Pipe *pipe = (struct Pipe *)data;
char buffer[1024] = "Message:";
ssize_t len;
while ((len = recv(pipe->fd_send, buffer + 8, 1000, 0)) > 0) {
send(pipe->fd_recv, buffer, len + 8, 0);
}
return NULL;
}
int main(int argc, char **argv) {
int port = atoi(argv[1]);
int fd;
if ((fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) {
perror("socket");
return 1;
}
struct sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = INADDR_ANY;
addr.sin_port = htons(port);
socklen_t addr_len = sizeof(addr);
if (bind(fd, (struct sockaddr *)&addr, sizeof(addr))) {
perror("bind");
return 1;
}
if (listen(fd, 2)) {
perror("listen");
return 1;
}
int fd1 = accept(fd, NULL, NULL);
int fd2 = accept(fd, NULL, NULL);
if (fd1 == -1 || fd2 == -1) {
perror("accept");
return 1;
}
pthread_t thread1, thread2;
struct Pipe pipe1;
struct Pipe pipe2;
pipe1.fd_send = fd1;
pipe1.fd_recv = fd2;
pipe2.fd_send = fd2;
pipe2.fd_recv = fd1;
pthread_create(&thread1, NULL, handle_chat, (void *)&pipe1);
pthread_create(&thread2, NULL, handle_chat, (void *)&pipe2);
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
return 0;
}