正如前面的答案所提到的,您需要创建一个数据包来序列化并通过网络发送。
因此,下面的示例适用于 DGRAM 套接字,但也适用于 STREAM 套接字的一些更改
第一步创建您自己的数据包。例如:
typedef struct messageInfo
{
char clientReq[MAX_LENGTH];
u_int32_t arg;
u_int32_t value;
//maybe add arglist // maybe send less data by encoding
/* required in case of unreliable connection for end packet***u_int16_t end;*** */
}__attribute__ ((__packed__))info;
第二步通过套接字伪代码发送它。
fd = socket( family, TYPE, 0 ); //TYPE = SOCK_STREAM or SOCK_DGRAM
//bind locally
//update peer sock structure to sendto or write
//create header start
uint8_t *tBuf = malloc(sizeof (info));
//memset to zero
info *pHeader = (info *)tBuf;
pHeader->value = htonl(19); //local value to send
pHeader->clientReq = "plus";
pheader->arg = htonl(23);
//create header end
//send to receiver
sendto(serverSock, tBuf, sizeof(info),0
,(struct sockaddr *) &peerV4,
sizeof(peerV4));
第三步接收伪代码
//create fd and init
//recvfrom allocate buffer to recv
uint8_t *recvBuf = malloc(sizeof(info));
info *pheader = (info *)recvBuf;
int currLen = recvfrom( fd, recvBuf,
sizeof(info),0,(struct sockaddr *)&peerV4,
&sockaddrLen);
//error handling
if(currLen == sizeof(info))
{
//close socket if end is specified in case of connection less protocol
// strcpy to localRecv
char *localRecv = malloc(MAX_LENGTH);
strcpy (localRecv,pheader->clientReq);
//do something with the values on the server like
if (strcasecmp(localRecv,"plus") == 0) //pseudo
plus(ntohl(pheader->arg),ntohl(pheader->value));
}