• 简单实现客户端服务端互联通信


     /*服务端程序*/
    #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) ", 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 ");
             exit(0);
      }
      if((ret=listen(sockfd,10))  < 0)
      {
        printf("listen failed ");
        exit(0);
       }
      theirlen=sizeof(theiraddr);
      if((newfd=accept(sockfd,(struct sockaddr *)&theiraddr,&theirlen))  < 0)
      {
        printf("accept failed ");
        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 ");
        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 ");
                  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;
    }

    代码完整,可直运行

  • 相关阅读:
    关闭caffe日志输出
    学习与工作中的认真和不认真
    深度学习_吴恩达_简单笔记
    JavaSE、JavaEE和JavaME的区别
    teamviewer
    提高深度学习检测网络准确率方法_未完待续
    提高深度学习分类模型准确率方法
    jQuery图片提示示例
    jQuery简单导航示例
    css盒子模型
  • 原文地址:https://www.cnblogs.com/cyyljw/p/9188590.html
Copyright © 2020-2023  润新知