socket 映射服务器程序
Posted Malphite
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了socket 映射服务器程序相关的知识,希望对你有一定的参考价值。
server
#include <stdio.h> #include <sys/types.h> /* See NOTES */ #include <sys/socket.h> #include <unistd.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <string.h> #include <stdlib.h> int listenfd; listenfd = socket(PF_INET,SOCK_STREAM,0); if(listenfd < 0) { printf("creat socket failed\n"); exit(1); } struct sockaddr_in servaddr; memset(&servaddr,0,sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_port = htons(5188); servaddr.sin_addr.s_addr = htonl(INADDR_ANY);//host any address if(bind(listenfd,(struct sockaddr*)&servaddr,sizeof(servaddr))<0) { printf("bind fialed\n"); exit(1); } if(listen(listenfd,SOMAXCONN)<0) { printf("listen failed\n"); exit(1); } struct sockaddr_in peeraddr; socklen_t peerlen = sizeof(peeraddr); int conn; if((conn=accept(listenfd,(struct sockaddr*)&peeraddr,&peerlen))<0) { printf("accept failed\n"); exit(1); } printf("ip=%s, port=%d\n",inet_ntoa(peeraddr.sin_addr),ntohs(peeraddr.sin_port )); char recvbuf[1024]; while(1) { memset(recvbuf,0,sizeof(recvbuf)); int ret = read(conn,recvbuf,sizeof(recvbuf)); fputs(recvbuf,stdout); write(conn,recvbuf,ret); } close(conn); close(listenfd); return 0; }
client
#include <stdio.h> #include <sys/types.h> /* See NOTES */ #include <sys/socket.h> #include <unistd.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <string.h> #include <stdlib.h> int main(void) { int sock; sock = socket(PF_INET,SOCK_STREAM,0); if(sock < 0) { printf("creat socket failed\n"); exit(1); } struct sockaddr_in servaddr; memset(&servaddr,0,sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_port = htons(5188); //servaddr.sin_addr.s_addr = htonl(INADDR_ANY);//host any address servaddr.sin_addr.s_addr = inet_addr("127.0.0.1"); if(connect(sock,(struct sockaddr*)&servaddr,sizeof(servaddr))<0) { printf("connect failed \n"); exit(1); } char sendbuf[1024] = {0}; char recvbuf[1024] = {0}; while(fgets(sendbuf,sizeof(sendbuf),stdin) != NULL) { write(sock,sendbuf,strlen(sendbuf)); read(sock,recvbuf,sizeof(recvbuf)); fputs(recvbuf,stdout); memset(recvbuf,0,sizeof(recvbuf)); } close(sock); return 0; }
以上是关于socket 映射服务器程序的主要内容,如果未能解决你的问题,请参考以下文章
错误 3002:映射片段中的问题 | c# linq 到实体