C++ IOCP windows??????
???????????? ???????[ 2014/9/3 11:42:19 ] ????????C++ NET ??????
????SOCKET????????
// IOCPClient.cpp : ??????????ó????????
//
#include "stdafx.h"
#include <iostream>
#include <cstdio>
#include <string>
#include <cstring>
#include <winsock2.h>
#include <Windows.h>
using namespace std;
#pragma comment(lib?? "Ws2_32.lib") // Socket???????????????
SOCKET sockClient; // ??????????????
HANDLE bufferMutex; // ???????????????????????????
const int DefaultPort = 9999;
int _tmain(int argc?? _TCHAR* argv[])
{
// ????socket????????(dll)
WORD wVersionRequested;
WSADATA wsaData; // ????????????Wjndows Socket????????
wVersionRequested = MAKEWORD( 2?? 2 ); // ????2.2?汾??WinSock??
int err = WSAStartup( wVersionRequested?? &wsaData );
if ( err != 0 ) { // ???????????????????????WSAStartup
return -1;
}
if ( LOBYTE( wsaData.wVersion ) != 2 || HIBYTE( wsaData.wVersion ) != 2 ) { // ???汾????????
WSACleanup( );
return -1;
}
// ????socket?????????????????????????????sockClient
sockClient = socket(AF_INET?? SOCK_STREAM?? 0);
if(sockClient == INVALID_SOCKET) {
printf("Error at socket():%ld "?? WSAGetLastError());
WSACleanup();
return -1;
}
// ???????sockClient?????????????
// int connect( SOCKET s?? const struct sockaddr* name?? int namelen);
// ????????????????????????????????
// ????????????趨???????????????
// ????????????????????
SOCKADDR_IN addrSrv;
addrSrv.sin_addr.S_un.S_addr = inet_addr("127.0.0.1"); // ?????·?????127.0.0.1;
addrSrv.sin_family = AF_INET;
addrSrv.sin_port = htons(DefaultPort);
while(SOCKET_ERROR == connect(sockClient?? (SOCKADDR*)&addrSrv?? sizeof(SOCKADDR))){
// ??????????????????????????
cout << "????????????????????????????Y/N):";
char choice;
while(cin >> choice && (!((choice != 'Y' && choice == 'N') || (choice == 'Y' && choice != 'N')))){
cout << "?????????????????:";
cin.sync();
cin.clear();
}
if (choice == 'Y'){
continue;
}
else{
cout << "???????...";
system("pause");
return 0;
}
}
cin.sync();
cout << "???????????????????????????????????????????????? ";
send(sockClient?? " Attention: A Client has enter... "?? 200?? 0);
bufferMutex = CreateSemaphore(NULL?? 1?? 1?? NULL);
DWORD WINAPI SendMessageThread(LPVOID IpParameter);
DWORD WINAPI ReceiveMessageThread(LPVOID IpParameter);
HANDLE sendThread = CreateThread(NULL?? 0?? SendMessageThread?? NULL?? 0?? NULL);
HANDLE receiveThread = CreateThread(NULL?? 0?? ReceiveMessageThread?? NULL?? 0?? NULL);
WaitForSingleObject(sendThread?? INFINITE); // ?????????
closesocket(sockClient);
CloseHandle(sendThread);
CloseHandle(receiveThread);
CloseHandle(bufferMutex);
WSACleanup(); // ???????????????
printf("End linking... ");
printf(" ");
system("pause");
return 0;
}
DWORD WINAPI SendMessageThread(LPVOID IpParameter)
{
while(1){
string talk;
char talkbuffer[200];
//gets(talkbuffer);
int iRand = rand()%3;
Sleep(iRand * 1000);
if(1 == iRand)
{
talkbuffer[0]='0';
}
else
{
talkbuffer[0]='1';
}
talkbuffer[1] = '