标签:
服务器端
#include <stdio.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <cstring>
#include <sys/types.h>
#include <stdlib.h>
#include <netinet/in.h>
#include <unistd.h>
int main(void)
{
printf("a1\n");
int listenfd;//创建一个socket
if( (listenfd=socket(PF_INET,SOCK_STREAM,IPPROTO_TCP))<0)
printf("socket errer");
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);//初始化地址
int on=1;
if(setsockopt(listenfd,SOL_SOCKET,SO_REUSEADDR,&on,sizeof(on))<0)//监听
printf("setsockopt error");
if(bind(listenfd,(struct sockaddr *)&servaddr,sizeof(servaddr))<0)///绑定地址
printf("bind errer");
if(listen(listenfd,SOMAXCONN)<0)
printf("listen errer");
struct sockaddr_in peeraddr;
socklen_t peerlen=sizeof(peeraddr);
int conn;
if((conn=accept(listenfd,(struct sockaddr*)&peeraddr,&peerlen))<0)
printf("accept errer");
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);
printf("a2\n");
return 0;
}
客户端
#include <stdio.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <cstring>
#include <sys/types.h>
#include <stdlib.h>
#include <netinet/in.h>
#include <unistd.h>
int main(void)
{
printf("b1\n");
int sock;
if( (sock=socket(PF_INET,SOCK_STREAM,IPPROTO_TCP))<0)
printf("socket errer");
struct sockaddr_in servaddr;
memset(&servaddr,0,sizeof(servaddr));
servaddr.sin_family=AF_INET;
servaddr.sin_port=htons(5188);
servaddr.sin_addr.s_addr=inet_addr("127.0.0.1");
if(connect(sock,(struct sockaddr*)&servaddr,sizeof(servaddr))<0)
printf("connect errer");
char sendbuf[1024]={0};
char recvbuf[1024]={0};
while(fgets(sendbuf,sizeof(sendbuf),stdin)!=NULL)
{
write(sock,sendbuf,strlen(sendbuf));
read(sock,recvbuf,strlen(recvbuf));
fputs(recvbuf,stdout);
}
close(sock);
printf("b2\n");
return 0;
}
标签:
原文地址:http://www.cnblogs.com/cqhstyle/p/4789945.html