簡單實現用戶端服務端互聯通訊

來源:互聯網
上載者:User

標籤:write   cep   pes   lib   string   family   listen   out   ons   

 /*服務端程式*/
#include <stdio.h>
#include <stdlib.h>
#include<sys/types.h>
#include<sys/socket.h>
#include <string.h>
#include <string.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <errno.h>


int main(void)
{
  int sockfd,ret,newfd;
  int readlen;
  int theirlen;
  char recv[100]={0};
  struct sockaddr_in myaddr;
  struct sockaddr_in theiraddr;
  if((sockfd=socket(AF_INET,SOCK_STREAM,0)) < 0)
  {
    printf("socket failed(%s)\n", strerror(errno));
    exit(0);
  }
  memset(&myaddr,0,sizeof(myaddr));
  myaddr.sin_family=AF_INET;
  myaddr.sin_port =htons(3490);
  myaddr.sin_addr.s_addr=htonl(INADDR_ANY);
  if((ret=bind(sockfd,(struct sockaddr *)&myaddr,sizeof(myaddr))) < 0)
  {
    printf("bind failed\n");
         exit(0);
  }
  if((ret=listen(sockfd,10))  < 0)
  {
    printf("listen failed\n");
    exit(0);
   }
  theirlen=sizeof(theiraddr);
  if((newfd=accept(sockfd,(struct sockaddr *)&theiraddr,&theirlen))  < 0)
  {
    printf("accept failed\n");
    exit(0);
  }
  while(1)
  {
    memset(recv,0,sizeof(recv));
    readlen=read(newfd,recv,sizeof(recv));
    fputs(recv,stdout);
    write(newfd,recv,readlen);
  }
  close(newfd);
  close(sockfd);

  return 0;

}

 

/*用戶端程式*/
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <string.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <errno.h>


int main(void)
{
  int sockfd,ret;
  int readlen;
  char send[100]={0};
  char recv[100]={0};
  struct sockaddr_in myaddr;
  if((sockfd=socket(AF_INET,SOCK_STREAM,0)) < 0)
  {
    printf("socket failed\n");
    exit(1);
  }
  memset(&myaddr,0,sizeof(myaddr));
  myaddr.sin_family=AF_INET;
  myaddr.sin_port =htons(3490);
  myaddr.sin_addr.s_addr=inet_addr("192.168.1.110");


  if((ret=connect(sockfd,(struct sockaddr *)&myaddr,sizeof(myaddr))) < 0)
  {
    printf("connect failed\n");
              exit(1);
       }
  while(1)
  {
    memset(recv,0,sizeof(recv));
    memset(send,0,sizeof(send));
    if(fgets(send,sizeof(send),stdin) !=NULL)
    {
      write(sockfd,send,sizeof(send));
      read(sockfd,recv,sizeof(recv));
      fputs(recv,stdout);
    }
  }
  close(sockfd);
  return 0;
}

代碼完整,可直運行

簡單實現用戶端服務端互聯通訊

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.