资源描述:
《基于TCP协议下的Linux网络编程的服务器端和客户端.doc》由会员上传分享,免费在线阅读,更多相关内容在教育资源-天天文库。
1、基于TCP协议下的Linux网络编程的服务器端和客户端客户端:Client.c/***************************************************Name:LinuxClient**Date:2014-11-10**Author:marksman**Aim:LinuxClientcansendandreceive**message.***************************************************/#include#include
2、#include#include#include#includeintmain(intargc,char*argv[]){intsocketfd,receive_socket;structsockaddr_ins_add,c_add;unsignedshortportnum=0x22B8;intlen;charbuf[100];/**Createthesocket*/if((socketfd=socket
3、(AF_INET,SOCK_STREAM,0))<0){printf("Socketcreateerror!");exit(1);}/**settheaddressformat*/bzero(&s_add,sizeof(structsockaddr_in));s_add.sin_family=AF_INET;s_add.sin_addr.s_addr=inet_addr("127.0.0.1");//changethestringto32-bitinternetbyte.s_add.sin_port=htons(p
4、ortnum);if(connect(socketfd,(structsockaddr*)(&s_add),sizeof(structsockaddr))<0){printf("Connectfailure!");return-1;}elseprintf("ConnectSuccess!");/**Usingthelooptosendandreceivethemessage.*/while(1){memset(buf,' ',100);printf("Inputmessagetosend:");fgets(b
5、uf,100,stdin);len=send(socketfd,buf,strlen(buf)-1,0);if(len<0){printf("senderror!");exit(1);}else{printf("SendSuccess!sendis:%s",buf);}memset(buf,' ',100);len=recv(socketfd,buf,100,0);if(len<0){printf("recverror!");exit(1);}elseif(0==len){printf("clientqu
6、it!");exit(1);}else{printf("receivemessageis:%s",buf);}printf("--------------------------");}close(socketfd);}服务器端:Server.c/***************************************************Name:LinuxServer**Date:2014-11-10**Author:marksman**Aim:LinuxServercansendandrece
7、ive**message.Itisatomsystemabout**InstantMessagingsystem.***************************************************/#include#include#include#include#include#include#includeintmain(intargc,
8、char*argv[]){intsocketfd_listen,socketfd_connect;structsockaddr_inserver_addr,client_addr;unsignedshortportnum=0x22B8;intlen;charbuf[100];/**Createthesocket*/if((sock