#include "sock.h" #pragma comment(lib, "ws2_32.lib") #ifdef WIN32 Sock Connect(char *ip,int port){ if(0 == ip){ return -1; } WORD wVersionRequested; WSADATA wsaData; int err; wVersionRequested = MAKEWORD(2,0); err = WSAStartup(wVersionRequested,&wsaData);// SOCKET ret = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);//create socket if(ret < 0){ printf("error malloc socket%d\r\n",ret); exit(0); } SOCKADDR_IN addrSrv; addrSrv.sin_addr.S_un.S_addr = inet_addr(ip);//"49.152.49.84"); addrSrv.sin_family = AF_INET; addrSrv.sin_port = htons(port); if(SOCKET_ERROR==connect(ret,(SOCKADDR*)&addrSrv,sizeof(SOCKADDR))){ closesocket(ret); DWORD gle = WSAGetLastError(); printf("connect socket error code %ld\r\n",gle); return -1; } return ret; } int Send(Sock s,char*dat, int len){ fd_set wFds; FD_ZERO(&wFds); FD_SET(s,&wFds); int ret = select(s + 1,0,&wFds,0,0); // time expire if(ret == 0){ return 0; }else if(ret > 0){ if(FD_ISSET(s,&wFds)){ int recv = send(s,dat,len,0); if(recv < 0) { closesocket(s); return -2; } return recv; } }else{ printf("error code %d\r\n",ret); return -1; } } int Recv(Sock s,char *rec,int len){ fd_set rFds; fd_set eFds; FD_ZERO(&rFds); FD_SET(s,&rFds); int ret = select(s + 1,&rFds,0,0,0); // time expire if(ret == 0){ return 0; }else if(ret > 0){ if(FD_ISSET(s,&rFds)){ int recvDat = recv(s,rec,len,0); if(recvDat <0) { closesocket(s); return -1; } return recvDat; } if(FD_ISSET(s,&eFds)){ closesocket(s); return -3; } } return -1; } #endif