unionSocket.cpp 2.05 KB
/* 
 *  Copyright (c) 2011,  广州江南科友union  
 *  All rights reserved. 
 *  文件名称: unionSocket.cpp
 *  摘 要:    实现socket功能基本的函数  
 *  当前版本: 1.0,  编写者: 杨武,修改时间: 2011-11-22 修改内容: 创建
 *  
 */
#include "stdafx.h"

#pragma comment(lib,"WS2_32.lib")

#ifdef _DEBUG
#define new DEBUG_NEW
#endif

int socketConnect(char *ip,int port)
{
	// TODO: 在此添加控件通知处理程序代码#include <winsock2.h>	// 为了使用Winsock API函数
	int client;
	WSADATA wsaData;
	WORD sockVersion = MAKEWORD(2, 0);
	::WSAStartup(sockVersion, &wsaData);

	// 创建套节字
	client = ::socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
	if(client == INVALID_SOCKET)
	{
		::WSACleanup();
		return INVALID_SOCKET ;
	}

	// 也可以在这里调用bind函数绑定一个本地地址

	// 填写远程地址信息
	sockaddr_in servAddr; 
	servAddr.sin_family = AF_INET;
	servAddr.sin_port = htons(port);
	servAddr.sin_addr.S_un.S_addr = inet_addr(ip);

	if(::connect(client, (sockaddr*)&servAddr, sizeof(servAddr)) == -1)
	{
		::WSACleanup();
		return  INVALID_SOCKET;
	}
	unsigned long arg = 0;   
    ioctlsocket(client,FIONBIO, &arg);//设置阻塞模式  
	return client;	
}
int socketSend(int sockId,char *pValue,int len)
{
	if (send(sockId,pValue,len,0) != len)
	{
		return unionSocketSendErr;
	}
	return(len);
}
int socketReceive(int sockId,char *pValue,int len,int timeout)
{
	int rc = -1;
    if(::setsockopt(sockId,SOL_SOCKET,SO_RCVTIMEO,(char *)&timeout,sizeof(timeout))==SOCKET_ERROR)
    {
      return unionSocketSetErr;
    }

	if ((rc = recv(sockId,pValue,len,0)) < 0)
	{
		return unionSocketRevErr;
	}
	return(rc);
}
int socketDisconnect(int sockId)
{
	// 关闭套节字
	::closesocket(sockId);
	// 释放WS2_32库
	::WSACleanup();	
	return 0;
}

int socketHandle(int sckid,char *in,int inlen,char *out,int timeout)
{
	char ret_buf[1025] = {0};
	int	 ret_len = 0;
	int  rc = 0;
	memset(ret_buf,0,1025);
	if ((rc = socketSend(sckid,in,inlen))!=inlen)
	{
		return unionSocketSendErr;
	}

	if ((ret_len = socketReceive(sckid,ret_buf,1024,timeout)) < 0)
	{
		return unionSocketRevErr;
	}

	memcpy(out,ret_buf,ret_len+1);
	return(ret_len);
}