updated version, but need to update installation scripts
[cls.git] / Extras / sockets / echotest.c
blob542855a9f165e720242dd3432dc83bc98ca1bee6
1 #if defined(__MWERKS__) && defined(macintosh)
2 # define MACINTOSH
3 #elif defined(_Windows)
4 typedef long ssize_t
5 #endif
7 #include <stdio.h>
8 #include <stdlib.h>
9 #include <unistd.h>
10 #include <errno.h>
11 #ifndef MACINTOSH
12 # include <sys/types.h>
13 #endif
14 #include "sock.h"
16 #define BLKSIZE 1024
18 #ifdef __MWERKS__
19 #include <console.h>
20 void main(void)
22 char **argv;
23 int argc = ccommand(&argv);
24 #else
25 void main(int argc, char *argv[])
27 #endif
28 Sock_port_t portnumber = 7;
29 int sockfd;
30 ssize_t bytesread, i;
31 ssize_t byteswritten;
32 char buf[BLKSIZE];
33 char *hostname = "localhost";
35 switch (argc) {
36 case 3: portnumber = atoi(argv[2]);
37 case 2: hostname = argv[1];
38 case 1: break;
39 default:
40 fprintf(stderr, "Usage: %s host port\n", argv[0]);
41 exit(1);
44 if (Sock_init() != 0) {
45 fprintf(stderr, "Sock initialization failed");
46 exit(1);
49 if ((sockfd = Sock_connect(portnumber, hostname, NULL)) < 0) {
50 perror("Unable to establish an Internet connection");
51 exit(1);
53 fprintf(stderr, "Connection has been made to %s\n", hostname);
55 for ( ; ; ) {
56 for (bytesread = 0; bytesread < BLKSIZE; bytesread++) {
57 int ch = getc(stdin);
58 if (ch == EOF)
59 break;
60 else if (ch == '\n') {
61 buf[bytesread++] = ch;
62 break;
64 else
65 buf[bytesread] = ch;
67 if (bytesread <= 0) break;
68 else {
69 byteswritten = Sock_write(sockfd, buf, bytesread, NULL);
70 if (byteswritten != bytesread) {
71 fprintf(stderr,
72 "Error writing %ld bytes, %ld bytes written\n",
73 (long)bytesread, (long)byteswritten);
74 break;
77 bytesread = Sock_read(sockfd, buf, BLKSIZE, NULL);
78 for (i = 0; i < bytesread; i++)
79 putc(buf[i], stdout);
82 Sock_close(sockfd, NULL);
83 exit(0);