红联Linux门户
Linux帮助

Ubuntu下用C语言实现客户端服务器交互

发布时间:2017-01-11 10:02:44来源:linux网站作者:JQ_AK47
Socket-Server.c
服务端代码
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
int main(void)
{
int listenfd = 0,connfd = 0;
struct sockaddr_in serv_addr;
char sendBuff[1025];  
int numrv;  
listenfd = socket(AF_INET, SOCK_STREAM, 0);
printf("socket retrieve success\n");
memset(&serv_addr, '0', sizeof(serv_addr));
memset(sendBuff, '0', sizeof(sendBuff));
serv_addr.sin_family = AF_INET;    
serv_addr.sin_addr.s_addr = htonl(INADDR_ANY); 
serv_addr.sin_port = htons(5000);    
bind(listenfd, (struct sockaddr*)&serv_addr,sizeof(serv_addr));
if(listen(listenfd, 10) == -1){
printf("Failed to listen\n");
return -1;
}     
while(1)
{      
connfd = accept(listenfd, (struct sockaddr*)NULL ,NULL); // accept awaiting request
strcpy(sendBuff, "Message from server");
write(connfd, sendBuff, strlen(sendBuff));
close(connfd);    
sleep(1);
return 0;
}
第二步:编译
gcc Server.c -o Socket-Server.out
第三步:执行等待客户端链接
./Socket-Server.out
 
Socket Client.c
客户端代码
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <netdb.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <arpa/inet.h>
int main(void)
{
int sockfd = 0,n = 0;
char recvBuff[1024];
struct sockaddr_in serv_addr;
memset(recvBuff, '0' ,sizeof(recvBuff));
if((sockfd = socket(AF_INET, SOCK_STREAM, 0))< 0)
{
printf("\n Error : Could not create socket \n");
return 1;
}
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(5000);
serv_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
if(connect(sockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr))<0)
{
printf("\n Error : Connect Failed \n");
return 1;
}
while((n = read(sockfd, recvBuff, sizeof(recvBuff)-1)) > 0)
{
recvBuff[n] = 0;
if(fputs(recvBuff, stdout) == EOF)
{
printf("\n Error : Fputs error");
}
printf("\n");
}
if( n < 0)
{
printf("\n Read Error \n");
}
return 0;
}
第二步:编译
gcc Client.c -o Socket-Client
第三步:执行链接服务器
./Socket-Client
看到下面说明成功了:
Ubuntu下用C语言实现客户端服务器交互
 
本文永久更新地址:http://www.linuxdiyf.com/linux/27702.html