1 |
#include <stdio.h> |
2 |
#include <stdlib.h> |
3 |
|
4 |
#include "my_socket.h" |
5 |
#include "sockbuf.h" |
6 |
|
7 |
int server_idx; |
8 |
|
9 |
int server_read(void *client_data, int idx, char *data, int len) |
10 |
{ |
11 |
printf("%s\n", data); |
12 |
return(0); |
13 |
} |
14 |
|
15 |
int server_eof(void *client_data, int idx, int err, const char *errmsg) |
16 |
{ |
17 |
if (err && errmsg) printf("Error: %s\n", errmsg); |
18 |
printf("Server closed connection!\n"); |
19 |
exit(0); |
20 |
} |
21 |
|
22 |
int server_connect(void *client_data, int idx, const char *peer_ip, int peer_port) |
23 |
{ |
24 |
printf("Connected to server (%s %d)!\n", peer_ip, peer_port); |
25 |
//sslmode_on(idx, 0); /* 0 means client, 1 means server */ |
26 |
//zipmode_on(idx); |
27 |
linemode_on(idx); |
28 |
return(0); |
29 |
} |
30 |
|
31 |
static sockbuf_handler_t server_event = { |
32 |
"server", |
33 |
server_connect, server_eof, NULL, |
34 |
server_read, NULL |
35 |
}; |
36 |
|
37 |
int stdin_read(void *client_data, int idx, char *data, int len) |
38 |
{ |
39 |
data[len] = '\n'; |
40 |
sockbuf_write(server_idx, data, len+1); |
41 |
return(0); |
42 |
} |
43 |
|
44 |
int stdin_eof(void *client_data, int idx, int err, const char *errmsg) |
45 |
{ |
46 |
sockbuf_delete(idx); |
47 |
return(0); |
48 |
} |
49 |
|
50 |
static sockbuf_handler_t stdin_event = { |
51 |
"stdin", |
52 |
NULL, stdin_eof, NULL, |
53 |
stdin_read, NULL |
54 |
}; |
55 |
|
56 |
main (int argc, char *argv[]) |
57 |
{ |
58 |
int sock, port, stdin_idx; |
59 |
char *host; |
60 |
|
61 |
srand(time(0)); |
62 |
if (argc < 2) { |
63 |
host = "127.0.0.1"; |
64 |
port = 12345; |
65 |
} |
66 |
else if (argc == 2) { |
67 |
host = argv[1]; |
68 |
port = 12345; |
69 |
} |
70 |
else { |
71 |
host = argv[1]; |
72 |
port = atoi(argv[2]); |
73 |
} |
74 |
|
75 |
printf("Connecting to %s %d\n", host, port); |
76 |
sock = socket_create(host, port, NULL, 0, SOCKET_CLIENT | SOCKET_NONBLOCK); |
77 |
if (sock < 0) { |
78 |
perror("socket_create"); |
79 |
return(0); |
80 |
} |
81 |
server_idx = sockbuf_new(); |
82 |
sockbuf_set_sock(server_idx, sock, SOCKBUF_CLIENT); |
83 |
sockbuf_set_handler(server_idx, &server_event, NULL); |
84 |
//sslmode_init(); |
85 |
|
86 |
stdin_idx = sockbuf_new(); |
87 |
socket_set_nonblock(0, 1); |
88 |
sockbuf_set_sock(stdin_idx, 0, 0); |
89 |
sockbuf_set_handler(stdin_idx, &stdin_event, NULL); |
90 |
linemode_on(stdin_idx); |
91 |
while (1) { |
92 |
sockbuf_update_all(1000); |
93 |
} |
94 |
return(0); |
95 |
} |