Socket.cpp
上传用户:garry_shen
上传日期:2015-04-15
资源大小:45647k
文件大小:3k
- #include "stdafx.h"
- #include <windows.h>
- #include "wsa_xtra.h"
- #include "Socket.h"
- #include "..XMudClient.h"
- HWND hWinMain;
- u_long GetIPAddr(LPTSTR szHost)
- {
- LPHOSTENT lpstHost;
- u_long lAddr=INADDR_ANY;
- if(*szHost){
- lAddr=inet_addr(szHost);
- if((lAddr==INADDR_NONE)&&(strcmp(szHost,"255.255.255.255"))){
- lpstHost=gethostbyname(szHost);
- if(lpstHost)
- lAddr=*((u_long*)(lpstHost->h_addr));
- else
- lAddr=INADDR_ANY;
- }
- }
- return(lAddr);
- }
- SOCKET InitClient(PSOCKADDR_IN pstName,HWND hWnd,u_int nAsyncMsg)
- {
- int nRet;
- SOCKET hSock;
- hWinMain=hWnd;
- hSock=socket(AF_INET,SOCK_STREAM,0);
- if(hSock==INVALID_SOCKET) {
-
- }else{
- nRet=WSAAsyncSelect(hSock,hWnd,nAsyncMsg,(FD_CONNECT | FD_READ | FD_WRITE | FD_CLOSE));
- if(nRet==SOCKET_ERROR){
- closesocket(hSock);
- hSock=INVALID_SOCKET;
- }else{
- nRet=connect(hSock,(LPSOCKADDR)pstName,SOCKADDR_LEN);
- if(nRet==SOCKET_ERROR){
- int WSAErr=WSAGetLastError();
- if(WSAErr!=WSAEWOULDBLOCK){
- closesocket(hSock);
- hSock=INVALID_SOCKET;
- }
- }
- }
- }
- return(hSock);
- }
- int CloseConn(SOCKET &hSock,LPTSTR lpstrBuf,int len,HWND hWnd)
- {
- int nRet=0;
- TCHAR achDiscard[BUF_SIZE];
- int cbBytesToDo=len,cbBytesDone=0;
- if(hSock!=INVALID_SOCKET){
- if(hWnd){
- }
- nRet=shutdown(hSock,1);
- for(nRet=1;(nRet&&(nRet!=SOCKET_ERROR));){
- if(lpstrBuf){
- nRet=recv(hSock,&lpstrBuf[cbBytesDone],cbBytesToDo,0);
- if(nRet&&(nRet!=SOCKET_ERROR)){
- cbBytesToDo-=nRet;
- cbBytesDone+=nRet;
- }
- }else
- nRet=recv(hSock,(LPTSTR)achDiscard,BUF_SIZE,0);
- closesocket(hSock);
- }
- hSock=INVALID_SOCKET;
- }
- return(nRet);
- }
- extern CRITICAL_SECTION csSend;
- int SendData(SOCKET hSock,LPTSTR lpstrSendData,int nLen)
- {
- static int cbSentToServer=0;
- int nRet,nBytesSent=0;
- if(hSock!=INVALID_SOCKET){
- while(cbSentToServer<nLen){
- nRet=send(hSock,&lpstrSendData[cbSentToServer],nLen-cbSentToServer,0);
- if(nRet==SOCKET_ERROR){
- int WSAErr=WSAGetLastError();
- if(WSAErr!=WSAEWOULDBLOCK){
- return WS_ERROR;
- }
- return WS_WAIT;
- }
- cbSentToServer+=nRet;
- }
- }
- cbSentToServer=0;
- return WS_OK;
- }
- int RecvData(SOCKET hSock,LPTSTR lpstrBuf,int len)
- {
- int cbBytesRcvd=0;
- int nRet=0,WSAErr;
- while(cbBytesRcvd<len){
- nRet=recv(hSock,&(lpstrBuf[cbBytesRcvd]),len-cbBytesRcvd,0);
- if(nRet==SOCKET_ERROR){
- WSAErr=WSAGetLastError();
- if(WSAErr!=WSAEWOULDBLOCK){
- return WS_ERROR;
- }
- goto recv_end;
- }
- else if(nRet==0)
- goto recv_end;
- else
- cbBytesRcvd+=nRet;
- }
- recv_end:
- return(cbBytesRcvd);
- }