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 }