/* Author: bhw EMail: bhwshx@163.com Date: Thu 12 Mar 2009 03:27:49 PM CSTa*/ //实现最简单的网络聊天功能(客户端版) #include<unistd.h> #include<sys/socket.h> #include<netinet/in.h> #include<arpa/inet.h> #include<stdio.h> #include<stdlib.h> #include<string.h> #define BUFSIZE 2048 int main(int argc, char *argv[]) { int sockfd; pid_t pid; size_t rcvLen; struct sockaddr_in addr; char sendbuf[BUFSIZE], rcvbuf[BUFSIZE]; char from[30]; unsigned int port; if(argc != 3) { printf("Usage: %s [target ip] [target port]/n", argv[0]); return 1; } strcpy(from, argv[1]); port = atoi(argv[2]); printf("port %d is opened./n", port); sockfd = socket(AF_INET, SOCK_STREAM, 0); if(sockfd == -1) { perror("socket"); return 1; } bzero(&addr, sizeof(addr)); addr.sin_family = AF_INET; addr.sin_port = htons(port); addr.sin_addr.s_addr = inet_addr(argv[1]); if(connect(sockfd, (struct sockaddr *)&addr, sizeof(addr)) != 0) { perror("connect"); return 1; } printf("Connected to server./n"); read(sockfd, rcvbuf, sizeof(rcvbuf)); printf("%s/n", rcvbuf); pid = fork(); while(1) { if(pid == 0) { bzero(rcvbuf, BUFSIZE); if((rcvLen = read(sockfd, rcvbuf, sizeof(rcvbuf))) < 0) printf("read from server error/n"); else if(rcvLen > 0) printf("From %s: %s/n", from, rcvbuf); else return 1; } if(pid > 0) { bzero(sendbuf, BUFSIZE); if(fgets(sendbuf, BUFSIZE, stdin) != NULL) write(sockfd, sendbuf, strlen(sendbuf)); } } close(sockfd); return 0; }