Client端:
#include#include #include #include #include #include #include #include #include #define MAXLINE 1024int main(int argc,char **argv){ //char *servInetAddr = "10.68.6.28"; int socketfd; struct sockaddr_in sockaddr; char recvline[MAXLINE], sendline[MAXLINE]; int n; if(argc != 2) { printf("client \n"); exit(0); } printf("argv[0]=%s, argv[1]=%s\n", argv[0], argv[1]); socketfd = socket(AF_INET,SOCK_STREAM,0); memset(&sockaddr,0,sizeof(sockaddr)); sockaddr.sin_family = AF_INET; sockaddr.sin_port = htons(10004); //inet_pton(AF_INET,servInetAddr,&sockaddr.sin_addr); inet_pton(AF_INET,argv[1],&sockaddr.sin_addr); if((connect(socketfd,(struct sockaddr*)&sockaddr,sizeof(sockaddr))) < 0 ) { printf("connect error %s errno: %d\n",strerror(errno),errno); exit(0); } printf("send message to server\n"); fgets(sendline,1024,stdin); if((send(socketfd,sendline,strlen(sendline),0)) < 0) { printf("send mes error: %s errno : %d",strerror(errno),errno); exit(0); } close(socketfd); printf("exit\n"); exit(0);}
编译client:
gcc client.c -o client
server端:
#include#include #include #include #include #include #include #include #include #define MAXLINE 1024int main(int argc,char **argv){ int listenfd,connfd; struct sockaddr_in sockaddr; char buff[MAXLINE]; int n; memset(&sockaddr,0,sizeof(sockaddr)); sockaddr.sin_family = AF_INET; sockaddr.sin_addr.s_addr = htonl(INADDR_ANY); sockaddr.sin_port = htons(10004); listenfd = socket(AF_INET,SOCK_STREAM,0); bind(listenfd,(struct sockaddr *) &sockaddr,sizeof(sockaddr)); listen(listenfd,1024); printf("Please wait for the client information\n"); for(;;) { if((connfd = accept(listenfd,(struct sockaddr*)NULL,NULL))==-1) { printf("accpet socket error: %s errno :%d\n",strerror(errno),errno); continue; } n = recv(connfd,buff,MAXLINE,0); buff[n] = '\0'; printf("recv msg from client:%s",buff); close(connfd); } close(listenfd);}
编译server:
gcc server.c -o server
测试:
g562044@shz-p0000601fl:~/Test/socket$ ./server &
[1] 24041 g562044@shz-p0000601fl:~/Test/socket$ Please wait for the client informationg562044@shz-p0000601fl:~/Test/socket$ ./client 127.0.0.1
send message to server // client 输出内容 Hello world! // client 输出内容 exit recv msg from client:Hello world! // server 输出内容 g562044@shz-p0000601fl:~/Test/socket$