第七章 抽象IO / 7.4.3 socket bio

服务端:

              #include <stdio.h>

              #include <openssl/bio.h>

              #include <string.h>

             

              int     main()

              {

                     BIO                      *b=NULL,*c=NULL;

                     int                         sock,ret,len;

                     char               *addr=NULL;

                     char               out[80];

             

                     sock=BIO_get_accept_socket("2323",0);

                     b=BIO_new_socket(sock, BIO_NOCLOSE);

                     ret=BIO_accept(sock,&addr);

                     BIO_set_fd(b,ret,BIO_NOCLOSE);

                     while(1)

                     {

                            memset(out,0,80);

                            len=BIO_read(b,out,80);

                            if(out[0]=='q')

                                   break;

                            printf("%s",out);

                     }

                     BIO_free(b);

                     return 0;

       }

       客户端telnet此端口成功后,输入字符,服务端会显示出来(linux下需要输入回车)

      

       客户端:

#include <openssl/bio.h>

       int    main()

       {

              BIO *cbio, *out;

        int len;

        char tmpbuf[1024];

      

        cbio = BIO_new_connect("localhost:http");

        out = BIO_new_fp(stdout, BIO_NOCLOSE);

        if(BIO_do_connect(cbio) <= 0)

        {

               fprintf(stderr, "Error connecting to server\n");

        }

        BIO_puts(cbio, "GET / HTTP/1.0\n\n");

        for(;;)

        {

               len = BIO_read(cbio, tmpbuf, 1024);

               if(len <= 0) break;

               BIO_write(out, tmpbuf, len);

        }

        BIO_free(cbio);

        BIO_free(out);

        return 0;

    }

    说明:本示例用来获取本机的web服务信息。

    cbio = BIO_new_connect("localhost:http");用来生成建立连接到本地web服务的BIO

    out = BIO_new_fp(stdout, BIO_NOCLOSE);生成一个输出到屏幕的BIO

    BIO_puts(cbio, "GET / HTTP/1.0\n\n");通过BIO发送数据。

    len = BIO_read(cbio, tmpbuf, 1024);web服务响应的数据写入缓存,此函数循环调用

    直到无数据。

       BIO_write(out, tmpbuf, len);通过BIO打印收到的数据。