1 #include <winsock2.h>
2 #include "windows.h"
3 #pragma comment(lib, "ws2_32.lib")
4
5 #define THE_PORT 6666
6 #define THE_IP_ADDRESS "127.0.0.1"
7 #define XIN_TIAO_PORT 6667
8
9 extern HANDLE ReStartHandle;
10 BOOL XIN_TIAO = 1;
11
12 //心跳檢測函式
13 DWORD WINAPI XiaoTiaoFunc(LPVOID lpParam)
14 {
15 int status = 0;
16 WSADATA wsaData;
17 SOCKET MyConnectSocket = 0;
18 sockaddr_in SocketAddr = { 0 };
19 DWORD OutTemp = 0;
20 char nNetTimeout = 5;
21 char RecvTemp[3] = "";
22 WSAStartup(MAKEWORD(2, 2), &wsaData);
23 MyConnectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
24 SocketAddr.sin_family = AF_INET;
25 SocketAddr.sin_addr.s_addr = inet_addr(THE_IP_ADDRESS);
26 SocketAddr.sin_port = htons(XIN_TIAO_PORT);
27 if (connect(MyConnectSocket,
28 (SOCKADDR *)&SocketAddr,
29 sizeof(SocketAddr)) == SOCKET_ERROR)
30 {
31 WSACleanup();
32 return FALSE;
33 }
34
35 setsockopt(MyConnectSocket,
36 SOL_SOCKET,
37 SO_RCVTIMEO,
38 (char *)&nNetTimeout,
39 sizeof(int));
40 for ( ; ; )
41 {
42 Sleep(10000);
43 send(MyConnectSocket,
44 "Hi",
45 sizeof("Hi"),
46 0);
47 status=recv(MyConnectSocket,
48 RecvTemp,
49 3,
50 0);
51 if (!status)
52 {
53 break;
54 }
55
56 }
57 closesocket(MyConnectSocket);
58 SetEvent(ReStartHandle);
59 ExitThread(0);
60 }
61
62
63
64
65 BOOL CreateConnect(SOCKET *MySocketAddress)
66 {
67 WSADATA wsaData;
68 SOCKET MyConnectSocket = 0;
69 sockaddr_in SocketAddr = { 0 };
70 DWORD OutTemp = 0;
71 WSAStartup(MAKEWORD(2, 2), &wsaData);
72 MyConnectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
73 SocketAddr.sin_family= AF_INET;
74 SocketAddr.sin_addr.s_addr = inet_addr(THE_IP_ADDRESS);
75 SocketAddr.sin_port = htons(THE_PORT);
76 if (connect(MyConnectSocket,
77 (SOCKADDR *)&SocketAddr,
78 sizeof(SocketAddr)) == SOCKET_ERROR)
79 {
80 WSACleanup();
81 return FALSE;
82 }
83 //啟動一個心跳檢測執行緒
84 if (CreateThread(
85 NULL,
86 0,
87 XiaoTiaoFunc,
88 NULL,
89 0,
90 &OutTemp) == false)
91 {
92 return FALSE;
93 }
94 *MySocketAddress = MyConnectSocket;
95
96 }
97
98 BOOL RecvData(SOCKET MySocket,PVOID IN_BUFFER,BOOL YesOrNo)
99 {
100 char nNetTimeout = 5;
101 //是否阻塞
102 if (YesOrNo)
103 {
104 setsockopt(MySocket,
105 SOL_SOCKET,
106 SO_RCVTIMEO,
107 (char *)&nNetTimeout,
108 sizeof(int));
109 }
110
111 if (!recv(MySocket,
112 (char *)IN_BUFFER,
113 sizeof(IN_BUFFER),
114 0))
115 {
116 return FALSE;
117 }
118 if (*((DWORD *)IN_BUFFER)==0)
119 {
120 return FALSE;
121 }
122 return TRUE;
123 }
124
125 BOOL SendData(SOCKET MySocket, PVOID OUT_BUFFER,DWORD Size)
126 {
127 int Status = 0;
128 Status = send(MySocket,
129 (char *)OUT_BUFFER,
130 Size,
131 0);
132 if (!Status)
133 {
134 return FALSE;
135 }
136 }