posts - 496,comments - 227,trackbacks - 0

sockutil.cpp

#include "stdafx.h"
#include <iostream.h>
#include <winsock2.h>
#include "sockutil.h"
void ShowError(unsigned int nError)
{
void* lpMsgBuf;
FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM,
NULL,
nError,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPTSTR) &lpMsgBuf,
0, NULL );

cout <<"(" << nError << "):" << lpMsgBuf;
LocalFree(lpMsgBuf);
}
BOOL ErrorHandle(const char * position, BOOL condition, const char * file, unsigned int line)
{
if(!condition)
{
return condition;
}
cout <<file << "(" << line << ")" << endl;
cout <<position<< endl;
unsigned int nError = GetLastError();
ShowError(nError);
return condition;
}
void InitializeAddress(DWORD ip, UINT port, sockaddr_in & addr)
{
memset(&addr,0,sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_addr.s_addr= ip;
addr.sin_port = htons(port);
}
int SendData(SOCKET hSocket, const char * data, int length)
{
int result;
int pos = 0;
while(pos < length)
{
result = send(hSocket, data + pos, length - pos , 0);
if(result > 0 )
{
pos += result;
}else{
return result;
}
}
return length;
}

demo1.cpp

// demo1.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <stdio.h>
#include <winsock2.h>
#pragma comment(lib,"ws2_32")
#include "sockutil.h"
int main(int argc, char* argv[])
{
unsigned short wVersion;
WSADATA wsa;
wVersion = MAKEWORD(2,2);
if(ERRORHANDLE(WSAStartup(wVersion, &wsa) != 0))
{
return -1;
}
SOCKET hSocket;
int a = PROTO_ICMP;
hSocket = socket(AF_INET,SOCK_STREAM,0);
if(ERRORHANDLE(hSocket == INVALID_SOCKET))
{
WSACleanup();
return -1;
}
sockaddr_in addr;
InitializeAddress(INADDR_ANY, 2000, addr);
if(ERRORHANDLE(SOCKET_ERROR == bind(hSocket, (const sockaddr*) & addr, sizeof(addr))))
{
closesocket(hSocket);
WSACleanup();
return -1;
}
if(ERRORHANDLE(SOCKET_ERROR == listen(hSocket,5)))
{
closesocket(hSocket);
WSACleanup();
return -1;
}
SOCKET hClient;
int size;
char buffer[2048];
int length;
size = sizeof(addr);
while(INVALID_SOCKET != (hClient = accept(hSocket,(sockaddr*)&addr, & size)))
{
size = sizeof(addr);
while((length = recv(hClient, buffer, sizeof(buffer),0)) > 0)
{
SendData(hClient,buffer, length);
}
closesocket(hClient);
}
closesocket(hSocket);
WSACleanup();
return 0;
}
posted on 2008-07-03 15:21 SIMONE 阅读(285) 评论(0)  编辑  收藏 所属分类: C++

只有注册用户登录后才能发表评论。


网站导航: