mirror of
https://github.com/fumiama/simple-dict.git
synced 2026-06-16 08:20:29 +08:00
优化发送速度,丰富client功能,解决半开问题
This commit is contained in:
55
client.c
55
client.c
@@ -7,23 +7,42 @@
|
||||
#include <netinet/in.h>
|
||||
#include <sys/socket.h>
|
||||
#include <arpa/inet.h>
|
||||
#include <sys/stat.h>
|
||||
#include <pthread.h>
|
||||
|
||||
#if !__APPLE__
|
||||
#include <sys/sendfile.h>
|
||||
#else
|
||||
struct sf_hdtr hdtr;
|
||||
#endif
|
||||
|
||||
int sockfd;
|
||||
char buf[BUFSIZ];
|
||||
char bufr[BUFSIZ];
|
||||
struct sockaddr_in their_addr;
|
||||
pthread_t thread;
|
||||
uint32_t file_size;
|
||||
int recv_bin = 0;
|
||||
|
||||
void getMessage(void *p) {
|
||||
int c = 0;
|
||||
while((c = recv(sockfd, bufr, BUFSIZ, 0)) > 0) {
|
||||
printf("Recv %d bytes: ", c);
|
||||
for(int i = 0; i < c; i++) putchar(bufr[i]);
|
||||
if(recv_bin) {
|
||||
FILE* fp = fopen("dump.bin", "w+");
|
||||
fwrite(bufr, c, 1, fp);
|
||||
fclose(fp);
|
||||
} else for(int i = 0; i < c; i++) putchar(bufr[i]);
|
||||
putchar('\n');
|
||||
}
|
||||
}
|
||||
|
||||
off_t fileSize(const char* fname) {
|
||||
struct stat statbuf;
|
||||
if(stat(fname, &statbuf)==0) return statbuf.st_size;
|
||||
else return -1;
|
||||
}
|
||||
|
||||
int main(int argc,char *argv[]) { //usage: ./client host port
|
||||
ssize_t numbytes;
|
||||
puts("break!");
|
||||
@@ -44,10 +63,40 @@ int main(int argc,char *argv[]) { //usage: ./client host port
|
||||
while(1) {
|
||||
printf("Enter command:");
|
||||
scanf("%s",buf);
|
||||
numbytes = send(sockfd, buf, strlen(buf), 0);
|
||||
if(!strcmp(buf, "bin")) recv_bin = !recv_bin;
|
||||
else if(!strcmp(buf, "file")) {
|
||||
printf("Enter file path:");
|
||||
scanf("%s",buf);
|
||||
printf("Open:");
|
||||
puts(buf);
|
||||
FILE *fp = NULL;
|
||||
fp = fopen(buf, "rb");
|
||||
if(fp) {
|
||||
off_t len = 0;
|
||||
file_size = (uint32_t)fileSize(buf);
|
||||
#if __APPLE__
|
||||
struct iovec headers;
|
||||
headers.iov_base = &file_size;
|
||||
headers.iov_len = sizeof(uint32_t);
|
||||
hdtr.headers = &headers;
|
||||
hdtr.hdr_cnt = 1;
|
||||
if(!sendfile(fileno(fp), sockfd, 0, &len, &hdtr, 0)) puts("Send file success.");
|
||||
else puts("Send file error.");
|
||||
#else
|
||||
send(sockfd, &file_size, sizeof(uint32_t), 0);
|
||||
if(!sendfile(sockfd, fileno(fp), &len, file_size)) puts("Send file success.");
|
||||
else puts("Send file error.");
|
||||
#endif
|
||||
fclose(fp);
|
||||
printf("Send count:%lld\n", len);
|
||||
} else puts("Open file error!");
|
||||
} else {
|
||||
send(sockfd, buf, strlen(buf), 0);
|
||||
if(!strcmp(buf, "quit")) exit(EXIT_SUCCESS);
|
||||
}
|
||||
sleep(1);
|
||||
}
|
||||
} else perror("Create msg thread failed");
|
||||
close(sockfd);
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user