SOCKET连接——server和client简单通信实例

源码及注释:
#include
#include
#include
#include
#include
#include
/*

  • TCP服务器
  • 接收客户端发送的消息并打印
    */

int main(int argc, const char *argv[])
{
//create socket
int sockFd = socket(PF_INET,SOCK_STREAM,0);
if(sockFd < 0)
{
puts(“create socket error!”);
return -1;
}
printf(“create socket OK!\n”);
//bind
struct sockaddr_in servAddr = {0}; //地址结构
servAddr.sin_family = PF_INET; //设置为Internet协议族
servAddr.sin_port = htons(8888); //设置端口号,165535(11023已被知名服务使用)
servAddr.sin_addr.s_addr = inet_addr(“192.168.1.137”);//自己的IP地址
int ret = bind(sockFd,(struct sockaddr *)&servAddr,sizeof(servAddr));//绑定本地IP和端口号
if(ret < 0)
{
printf(“bind error!\n”);
close(sockFd);
return -1;
}
printf(“bind OK!\n”);
//listen
ret = listen(sockFd,1);
if(ret < 0)
{
perror(“listen error!”);
close(sockFd);
return -1;
}
printf(“listening:\n”);
//accept
int connFd = accept(sockFd,NULL,NULL);//客户端地址如果不关心,可置为NULL
if(connFd < 0)
{
perror(“accept error!”);
close(sockFd);
return -1;
}
printf(“accept OK!\n”);
//recv
char buf[1024];
while(ret = read(connFd,buf,sizeof(buf)) > 0)
{
if(ret < 0)
{
perror(“read error!”);
close(sockFd);
close(connFd);
return -1;
}
printf(“recv:%s\n”,buf);
if(strncmp(buf,“quit”,4) == 0)
{
printf(“quit OK!\n”);
break;
}
memset(buf,0,sizeof(buf));
}
//close
close(sockFd);
close(connFd);
return 0;
}

#include
#include
#include
#include
#include
#include

int main()
{
//create socket
int sockFd = socket(PF_INET,SOCK_STREAM,0);
if(sockFd < 0)
{
perror(“create socket error!”);
return -1;
}
printf(“create socket OK!\n”);
//请求连接
struct sockaddr_in servAddr = {0};
servAddr.sin_family = PF_INET;
servAddr.sin_port = htons(8888);
servAddr.sin_addr.s_addr = inet_addr(“192.168.1.137”);
int ret = connect(sockFd,(struct sockaddr *)&servAddr,sizeof(servAddr));
if(ret < 0)
{
perror(“connect error!”);
close(sockFd);
return -1;
}
printf(“connect OK!\n”);
//write
printf(“write to server:”);
char buf[1024];//字节流要一样大,服务器端设置为1024,这里也要是1024
while(1)
{
memset(buf,0,sizeof(buf));
gets(buf);
ret = write(sockFd,buf,sizeof(buf));
if(ret < 0)
{
perror(“write error!”);
close(sockFd);
return -1;
}
printf(“write OK!\n”);
if(strncmp(buf,“quit”,4) == 0)
break;
}
//close
close(sockFd);
return 0
}

你可能感兴趣的:(网络,服务器,c语言)