/[cvs]/eggdrop1.9/testcode/chat.c
ViewVC logotype

Contents of /eggdrop1.9/testcode/chat.c

Parent Directory Parent Directory | Revision Log Revision Log | View Revision Graph Revision Graph


Revision 1.1 - (show annotations) (download) (as text)
Tue Jan 8 00:09:09 2002 UTC (18 years, 2 months ago) by stdarg
Branch: MAIN
File MIME type: text/x-chdr
Err, I don't know if I already added these files or not, so I'll add them again.

1 #include <stdio.h>
2 #include "my_socket.h"
3 #include "sockbuf.h"
4
5 static int *idx_array = NULL;
6 static int array_len = 0;
7
8 static int client_read(int idx, sockbuf_iobuf_t *iobuf, void *client_data)
9 {
10 char buf[128];
11 int i, buflen;
12
13 iobuf->data[iobuf->len] = 0;
14 snprintf(buf, 128, "<%d> %s\n", idx, iobuf->data);
15 buflen = strlen(buf);
16 iobuf->data[iobuf->len++] = '\n';
17 for (i = 0; i < array_len; i++) {
18 if (idx_array[i] != idx) {
19 sockbuf_write(idx_array[i], buf, buflen);
20 }
21 }
22 return(0);
23 }
24
25 static int client_eof(int idx, void *ignore, void *client_data)
26 {
27 char buf[128];
28 int i, buflen;
29
30 for (i = 0; i < array_len; i++) {
31 if (idx_array[i] == idx) break;
32 }
33 array_len--;
34 memmove(idx_array+i, idx_array+i+1, sizeof(int) * (array_len-i));
35 sockbuf_delete(idx);
36 snprintf(buf, 128, "%d disconnected\n", idx);
37 buflen = strlen(buf);
38 for (i = 0; i < array_len; i++) {
39 sockbuf_write(idx_array[i], buf, buflen);
40 }
41 return(0);
42 }
43
44 static sockbuf_event_t client_handler = {
45 (Function) 4,
46 (Function) "client",
47 client_read,
48 NULL,
49 client_eof,
50 NULL
51 };
52
53 static int server_read(int idx, int serversock, void *client_data)
54 {
55 char buf[128];
56 int buflen, newsock, newidx, i;
57
58 newsock = accept(serversock, NULL, NULL);
59 if (newsock < 0) return(0);
60
61 socket_set_nonblock(newsock, 1);
62 newidx = sockbuf_new(newsock, 0);
63 zipmode_on(newidx);
64 linemode_on(newidx);
65 sockbuf_set_handler(newidx, client_handler, NULL);
66
67 printf("New connection %d\n", newidx);
68 snprintf(buf, 128, "New connection %d\n", newidx);
69 buflen = strlen(buf);
70 for (i = 0; i < array_len; i++) {
71 sockbuf_write(idx_array[i], buf, buflen);
72 }
73 idx_array = (int *)realloc(idx_array, sizeof(int) * (array_len+1));
74 idx_array[array_len] = newidx;
75 array_len++;
76 return(0);
77 }
78
79 static sockbuf_event_t server_handler = {
80 (Function) 1,
81 (Function) "server",
82 server_read
83 };
84
85 main ()
86 {
87 int sock, idx;
88
89 sock = socket_create(NULL, 12345, SOCKET_SERVER);
90 if (sock < 0) {
91 perror("socket_create");
92 return(0);
93 }
94 idx = sockbuf_new(sock, SOCKBUF_SERVER);
95 sockbuf_set_handler(idx, server_handler, NULL);
96 while (1) {
97 sockbuf_update_all(-1);
98 }
99 return(0);
100 }

webmaster@eggheads.org
ViewVC Help
Powered by ViewVC 1.1.23