unionSocket.cpp
2.05 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
/*
* 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);
}