标签:
data.h
1 #ifndef DATA_H 2 #define DATA_H 3 #include <stdio.h> 4 #include <string.h> 5 #include <sys/types.h> 6 #include <sys/stat.h> 7 #include <sys/socket.h> 8 #include <stdlib.h> 9 #include <unistd.h> 10 #include <netinet/in.h> 11 #include <arpa/inet.h> 12 #include <netdb.h> 13 #include <errno.h> 14 #define PORT 45178 15 #define maxn 1100 16 #define BACKLOG 10 17 #define IP "127.0.0.1" 18 #endif
server.c
#include "data.h" void send_message(int sockfd,struct sockaddr_in client) { int num; char sendbuf[maxn],recvbuf[maxn]; char cliname[maxn]; printf("You get a connection from %s \n",inet_ntoa(client.sin_addr)); num = recv(sockfd,cliname,maxn,0); printf("client name is %s\n",cliname); while(num = recv(sockfd,recvbuf,maxn,0)) { num--; recvbuf[num] = ‘\0‘; printf("Receive a message is %s from <===>%s\n",recvbuf,cliname); send(sockfd,recvbuf,maxn,0); } } int main() { int sockfd; struct sockaddr_in server_in; if((sockfd = socket(AF_INET,SOCK_STREAM,0)) == -1) { fprintf(stderr,"socket fail,error %s",strerror(errno)); return -1; } bzero(&server_in,sizeof(server_in)); server_in.sin_family = AF_INET; server_in.sin_port = htons(PORT); inet_pton(AF_INET,IP,&server_in.sin_addr); if(bind(sockfd,(struct sockaddr*)&server_in,sizeof(server_in)) == -1) { fprintf(stderr,"bind fail,error %s",strerror(errno)); return -1; } listen(sockfd,BACKLOG); struct sockaddr_in client; int len = sizeof(client); int afd; int pid; while(1) { if((afd = accept(sockfd,(struct sockaddr*)&client,&len)) == -1) { fprintf(stderr,"accept fail,error:%s\n",strerror(errno)); exit(1); } if((pid = fork()) > 0) { close(afd); continue; } else if(pid == 0) { close(sockfd); send_message(afd,client); exit(0); } else { printf("fork() error!\n"); exit(0); } } close(sockfd); }
client.c
#include "data.h" void send_message(FILE *fp,int sockfd) { char sendline[maxn]; char recvbuf[maxn]; int num; printf("connect to server!\n"); printf("Please input client name :\n"); if(fgets(sendline,maxn,fp) == NULL) { printf("input name error!\n"); exit(1); } send(sockfd,sendline,maxn,0); while(1) { printf("Please input message !\n"); if(fgets(sendline,maxn,fp) == NULL) break; send(sockfd,sendline,strlen(sendline),0); bzero(&recvbuf,sizeof(recvbuf)); recv(sockfd,recvbuf,maxn,0); int len = strlen(recvbuf); recvbuf[len] = ‘\0‘; printf("client receive message is %s\n",recvbuf); } printf("client exit!\n"); } int main() { struct sockaddr_in client_in; int sockfd; if((sockfd = socket(AF_INET,SOCK_STREAM,0)) == -1) { fprintf(stderr,"socket fail,error %s\n",strerror(errno)); return -1; } bzero(&client_in,sizeof(client_in)); client_in.sin_family = AF_INET; client_in.sin_port = htons(PORT); inet_pton(AF_INET,IP,&client_in.sin_addr); connect(sockfd,(struct sockaddr*)&client_in,sizeof(client_in)) ; send_message(stdin,sockfd); close(sockfd); return 0; }
标签:
原文地址:http://www.cnblogs.com/chenyang920/p/5592177.html