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
| #pragma once #include<iostream> #include<cstdlib> #include<unistd.h> #include<sys/socket.h> #include<sys/types.h> #include<cstring> #include<arpa/inet.h>
int writen(int _sockfd,const char *msg, int size) { const char *buf = msg; int count = size; while (count > 0) { int len = send(_sockfd, buf, count, 0); if (len == -1) { return -1; } else if (len == 0) { continue; } else { buf += len; count -= len; } } return size; }
void sendmsg(int _sockfd,const char *msg, int len) { char *data = (char *)malloc(sizeof(char) * (len + 4)); int biglen = htonl(len); memcpy(data, &biglen, 4); memcpy(data + 4, msg, len); int ret = writen(_sockfd,data, len + 4); if (ret == -1) { free(data); close(_sockfd); } else free(data); }
int readn(int _sockfd,char *buf, int size) { char *pt = buf; int count = size; while (count > 0) { int len = recv(_sockfd, pt, count, 0); if (len == -1) { return -1; } else if (len == 0) { return size - count; } else { pt += len; count -= len; } } return size; } int RecvMsg(int _sockfd,char **buf) {
int len = 0; readn(_sockfd,(char *)&len, 4); len = htonl(len); char *msg = (char *)malloc(sizeof(char) * (len + 1)); int size = readn(_sockfd,msg, len); if (size != len) { close(_sockfd); free(msg); return -1; } msg[size] = '\0'; *buf = msg; return size; }
|