设为首页 加入收藏

TOP

在Windows环境下实现一个简单的libevent服务器(三)
2017-10-10 12:02:52 】 浏览:9620
Tags:Windows 环境 实现 一个 简单 libevent 服务器
RSIST, do_accept_cb, (void*)base); 135 event_add(listen_event, NULL); 136 event_base_dispatch(base); 137 printf("The End."); 138 return 0; 139 }

客户端代码:Client.cpp

 1 /******* 客户端程序  client.c ************/
 2 #define _WINSOCK_DEPRECATED_NO_WARNINGS
 3 #define _CRT_SECURE_NO_WARNINGS
 4 #include <stdlib.h>  
 5 #include <stdio.h>  
 6 #include <errno.h>  
 7 #include <string.h>       
 8 #include<winsock2.h>
 9 #include<ws2tcpip.h>
10 #include<iostream>
11 
12 #pragma comment (lib,"ws2_32.lib")
13 int main(int argc, char *argv[])
14 {
15     WSADATA  Ws;
16     //Init Windows Socket
17     if (WSAStartup(MAKEWORD(2, 2), &Ws) != 0)
18     {
19         return 0;
20     }
21     int sockfd;
22     char buffer[1024];
23     struct sockaddr_in server_addr;
24     struct hostent *host;
25     int portnumber, nbytes;
26 
27     if ((host = gethostbyname("127.0.0.1")) == NULL)
28     {
29         fprintf(stderr, "Gethostname error\n");
30         exit(1);
31     }
32 
33     if ((portnumber = atoi("9999"))<0)
34     {
35         fprintf(stderr, "Usage:%s hostname portnumber\a\n", argv[0]);
36         exit(1);
37     }
38 
39     /* 客户程序开始建立 sockfd描述符  */
40     if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
41     {
42         fprintf(stderr, "Socket Error:%s\a\n", strerror(errno));
43         exit(1);
44     }
45 
46     /* 客户程序填充服务端的资料       */
47     memset(&server_addr,0, sizeof(server_addr));
48     server_addr.sin_family = AF_INET;
49     server_addr.sin_port = htons(portnumber);
50     server_addr.sin_addr = *((struct in_addr *)host->h_addr);
51 
52     /* 客户程序发起连接请求         */
53     if (connect(sockfd, (struct sockaddr *)(&server_addr), sizeof(struct sockaddr)) == -1)
54     {
55         fprintf(stderr, "Connect Error:%s\a\n", strerror(errno));
56         exit(1);
57     }
58 
59     while (true)
60     {
61         char MESSAGE[] = "hello server..\n";
62         //bufferevent_write(buf_ev,MESSAGE,strlen(MESSAGE));  
63         //  
64         if (-1 == (::send(sockfd, MESSAGE, strlen(MESSAGE), 0)))
65         {
66             printf("the net has a error occured..");
67             break;
68         }
69 
70         if ((nbytes = recv(sockfd, buffer, 1024,0)) == -1)
71         {
72             fprintf(stderr, "read error:%s\n", strerror(errno));
73             exit(1);
74         }
75 
76         buffer[nbytes] = '\0';
77         printf("I have received:%s\n", buffer);
78         memset(buffer, 0, 1024);
79 
80         Sleep(2);
81 
82     }
83     /* 结束通讯     */
84     closesocket(sockfd);
85     exit(0);
86 
87     return 0;
88 }

 

首页 上一页 1 2 3 下一页 尾页 3/3/3
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇php中数组和字符串的相互转换 下一篇PHPExcel 相关操作

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目