/** * 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 encoded ed * @ Author: mjn * @ create: 2011-11-02 * @ update: 2011-11-02 */INT readall (Socket socket, char * Buf, int N) {int nleft = N; /* remaining bytes */INT nbytes;/* Number of read bytes */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 socket, char * Buf, int N) {int nleft = N;/* remaining bytes */INT nbytes;/* Number of written nodes */char * PTR = Buf; /* point to the position of the string being written */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 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) encoding string of the default Chinese platform -- not necessarily utf8 string may be a GB2312-80 or GBK or 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 );}
Note:
Test environments: Microsoft Visual Studio 2010