/**
* mysock.h
* socket data transmission function prototype
* @author : MJN
* @create : 2011/11/27
* @update : 2011/11/27
*/
#include <WinSock2.h>
int readAll(SOCKET socket, char * buf, int n);
int writeAll(SOCKET socket, char * buf, int n);
int readInt(SOCKET socket, int *value);
int writeInt(SOCKET socket, int value);
int readString(SOCKET socket, char * str, int size);
int writeString(SOCKET socket, char * str);
/**
* mysock.c
* socket data transmission function
* @author : MJN
* @create : 2011/11/27
* @update : 2011/11/27
*/
#include "mysock.h"
/**
* @function : read n bytes from socket to buf
* @buf : store bytes that read from socket
* @return : the number of bytes received
* @author : MJN
* @create : 2011-11-02
* @update : 2011-11-02
*/
int readAll(SOCKET socket, char *buf, int n)
{
int nleft = n; /* 剩余字节数 */
int nbytes; /* 已读字节数 */
char *ptr = buf;
while (nleft > 0)
{
nbytes = recv(socket, ptr, nleft, 0);
if (nbytes < 0)
{
//printf("read error");
return -1;
}
if (nbytes == 0)
{
break; /* no more data to read */
}
nleft -= nbytes;
ptr += nbytes;
}
return n - nleft;
}
/**
* @function : write n bytes to socket
* @return : the number of bytes sent
* @author : MJN
* @create : 2011-11-02
* @update : 2011-11-02
*/
int writeAll(SOCKET socket, char *buf, int n)
{
int nleft = n; /* 剩余字节数 */
int nbytes; /* 已写字节数 */
char *ptr = buf; /* 指向正在写的字串位置 */
while (nleft > 0)
{
nbytes = send(socket, ptr, nleft, 0);
if (nbytes <= 0)
{
//printf("write error");
return -1;
}
nleft -= nbytes;
ptr += nbytes;
}
return n;
}
/**
* @function : read an integer(4 bytes)
* @return : the number of bytes read
* @author : MJN
* @create : 2011-11-02
* @update : 2011-11-02
*/
int readInt(SOCKET socket, int *value)
{
int n;
int ret = readAll(socket, (char *)&n, 4);
*value = ntohl(n);
return ret;
}
/**
* @function : write an integer(4 bytes)
* @return : the number of bytes write
* @author : MJN
* @create : 2011-11-02
* @update : 2011-11-02
*/
int writeInt(SOCKET socket, int value)
{
int n = htonl(value);
return writeAll(socket, (char *)&n, 4);
}
/**
* @function : read string(default encoding depends on platform)
默认中文平台的编码串--不一定是UTF8串
可能是GB2312-80或GBK或GB18030
* @return : the number of bytes read
* @author : MJN
* @create : 2011-11-02
* @update : 2011-11-02
*/
int readString(SOCKET socket, char *str, int size)
{
int len = 0;
int n = readInt(socket, &len);/* read length of string */
memset(str, 0, size);
n = readAll(socket, str, min(len, size - 1));
return n;
}
/**
* @function : write string(default encoding depends on platform)
* @return : the number of bytes write
* @author : MJN
* @create : 2011-11-02
* @update : 2011-11-02
*/
int writeString(SOCKET socket, char *str)
{
int len = strlen(str);
writeInt(socket, len);
return writeAll(socket, str, len);
}
注:
测试环境:Microsoft Visual Studio 2010