#include #include #include #include #include #include #include #include #include #include #include #include #include #include #include Display *display; XEvent event; Window root, win; XFontStruct *font; Colormap colormap; XColor color; GC gc; int screen, depth, white, black, cn, y = 20; char buffer[256]; int main(int argc, char *argv[]) { int sock, quit = 0; unsigned long hostname; char buff[1024], rb[1], sb[1024]; struct sockaddr_in inaddr; struct hostent *gethost; fd_set readfds; if (argc < 3) { printf("usage: %s [hostname] [port]\n", argv[0]); return 0; } if (!(display = XOpenDisplay(getenv("DISPLAY")))) { perror("XOpenDisplay"); printf("%s: unable to open display: %s\n", argv[0], getenv("DISPLAY")); exit(1); } memset(buffer, 0, sizeof(buffer)); screen = DefaultScreen(display); root = RootWindow(display, screen); white = WhitePixel(display, screen); black = BlackPixel(display, screen); colormap = DefaultColormap(display, screen); font = XLoadQueryFont(display, "*helveti*med*-r*12*"); cn = ConnectionNumber(display); win = XCreateSimpleWindow(display, root, 0, 0, 700, 400, 0, white, white); gc = XCreateGC(display, win, 0, 0); XSetForeground(display, gc, black); XSetFont(display, gc, font->fid); XSelectInput(display, win, ExposureMask); XMapWindow(display, win); XFlush(display); if ((gethost = gethostbyname(argv[1])) == NULL) { herror("gethostbyname"); exit(1); } hostname = inet_addr(inet_ntoa(*(struct in_addr *)gethost->h_addr)); inaddr.sin_family = AF_INET; inaddr.sin_addr.s_addr = hostname; inaddr.sin_port = htons(atoi(argv[2])); memset(&inaddr.sin_zero, 0, 8); memset(buff, 0, sizeof(buff)); sock = socket(AF_INET, SOCK_STREAM, 0); if (connect(sock, (struct sockaddr *)&inaddr, sizeof(inaddr)) == -1) { perror("connect"); exit(1); } fcntl(sock, F_SETFL, O_NONBLOCK); while (!quit) { FD_ZERO(&readfds); FD_SET(0, &readfds); FD_SET(cn, &readfds); FD_SET(sock, &readfds); memset(buffer, 0, strlen(buffer)); memset(sb, 0, strlen(sb)); rb[0] = 0; printf("connection %d, socket %d\n", cn, sock); select(sock+1, &readfds, NULL, NULL, NULL); if (FD_ISSET(sock, &readfds)) { int r; do { r = read(sock, rb, 1); if (r == -1 || r == 0) break; if (strcmp(rb, "") == 0) break; strcat(buffer, rb); } while (strcmp(rb, "\x0a") != 0); XDrawString(display, win, gc, 10, y, buffer, strlen(buffer)); y += 15; XFlush(display); } if (FD_ISSET(cn, &readfds)) { XNextEvent(display, &event); if (event.type == Expose) y = 10; } if (FD_ISSET(0, &readfds)) { read(0, sb, 10); send(sock, sb, strlen(sb), 0); // if (strcmp(buff, "quit") == 0) quit = 1; XDrawString(display, win, gc, 10, y, sb, strlen(sb)); y += 15; XFlush(display); fflush(0); } } return 0; }