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

前端之家收集整理的这篇文章主要介绍了Ubuntu下用C语言实现客户端服务器交互前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

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,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,sizeof(recvBuff));
  if((sockfd = socket(AF_INET,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相关文章