ubuntu16.04 socket传输文件
Posted COCO_PEAK_NOODLE
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ubuntu16.04 socket传输文件相关的知识,希望对你有一定的参考价值。
arupcsedu / SocketFileTransfer
参考网址https://github.com/arupcsedu/SocketFileTransfer#build-and-run-client
简单修改NWClient一个地方
char *dirName = argv[1]; //basename(argv[1]);
可以用了,其实Qt封装后的socket更简单,但是没有qt就试试这个吧!
编译系统:ubuntu16.04
作者步骤写的很详细
这是服务端server
/* File Name : NWServer.cpp
Author : Arup Sarker
Creation date : 12/28/2020
Description: Main responsibilities of this source are
1. Create socket and bind with client to a specific port
2. Receive file from client concurrently
3. Utility function to check file integrity by calculating checkSum
Notes: BSD socket apis are used and compiled with g++ in Ubuntu 18.04. For Other OS, files needs be cross compiled and create executable
*/
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <pthread.h>
#include <sys/file.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <assert.h>
#include <time.h>
#define MAX_LENGTH_OF_SINGLE_LINE 4096
#define LISTEN_PORT 8050
#define SERVER_PORT 5080
#define BUFFER_SIZE 100000
#define MAX_NAME 1000
#define MAX_THREAD 100
// ToDo: This will be Dynamic;
// Status: Done
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
void* socketThreadFT(void *arg);
//CheckSum Calculation
unsigned calculateChecksum(void *buffer, size_t len)
unsigned char *buf = (unsigned char *)buffer;
size_t i;
unsigned int checkSum = 0;
for (i = 0; i < len; ++i)
checkSum += (unsigned int)(*buf++);
return checkSum;
// This is a utility function for writing data into file
unsigned int fileWriter(char *fileName, int sockfd, FILE *fp)
// 11.1 Declare data length
int n;
// 11.2 Declare and Initialize buffer size
time_t t = time(NULL);
struct tm *tm = localtime(&t);
char s[64];
assert(strftime(s, sizeof(s), "%c", tm));
//printf("%s\\n", s);
printf("%s file Receiving is started in Connection ID: %d at : %s\\n", fileName, sockfd, s);
// 11.3 Receive data from socket and save into buffer
unsigned int checkSum = 0;
char buff[BUFFER_SIZE] = 0;
while(1)
n = recv(sockfd, buff, BUFFER_SIZE,0);
//printf("File is receiving from Socket : %d\\n", sockfd);
if (n == -1)
perror("Error in Receiving File");
exit(1);
if(n <= 0)
break;
//用于校验数据是否接收完整
checkSum += calculateChecksum(buff, n);
// 11.4 Read File Data from buffer and Write into file
// 11.4 从buffer读取数据,然后保存到file
if (fwrite(buff, sizeof(char), n, fp) != n)
perror("Error in Writing File");
exit(1);
// 11.5 Allocate buffer
memset(buff, '\\0', BUFFER_SIZE);
fclose(fp);
return checkSum;
void* socketThreadFT(void *arg)
//arg转换为connfd,用于接收数据,connfd就是该服务器中的客户端的id,用于区分不同的客户端
int connfd = *((int *)arg);
unsigned int checkSum = 0;
pthread_mutex_lock(&lock);
// 8. Receive incoming file from client
char filename[MAX_NAME] = 0;
//接收传递过来数据的文件名,用于保存
if (recv(connfd, filename, MAX_NAME,0) == -1)
perror("Unable to receive file due to connection or file error");
exit(1);
int fileLength = strlen(filename);
pthread_mutex_unlock(&lock);
sleep(1);
if(fileLength > 0)
// 9. After receiving from client, create file to save data
// 9.收到客户端传来的信息,开始创建文件来保存数据。从这就可以看出传递文件的本质,就是发送接收char数据,然后再保存在另外的地址。
//printf("File Name : %s\\n", filename);
//保存接收的数据
FILE *fp = fopen(filename, "wb");
if (fp == NULL)
perror("Unable to create File pointer");
exit(1);
// 10. Start receiving file Data and print in console
char addr[INET_ADDRSTRLEN];
// 11. Write the data into file.
// 11.开始保存数据到file
checkSum = fileWriter(filename, connfd, fp);
// 12. Print success message into console
// 12. 打印保存信息
time_t t = time(NULL);
struct tm *tm = localtime(&t);
char s[64];
assert(strftime(s, sizeof(s), "%c", tm));
printf("%s is received with checkSum %d at : %s\\n",filename, checkSum,s);
//断开客户端connfd
close(connfd);
pthread_exit(NULL);
int main(int argc, char *argv[])
// 1. Create TCP Socket
// 1.创建 TCP socket(Transfer Control Protocol 传输控制协议、 socket (电器上的)插口,插孔)
int sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd == -1)
perror("Unable to create Socket");
exit(1);
//线程mutex初始化,mutex是指一个线程进来后,其他线程就会被阻塞到这里,进不了下一步,原理是啥?感觉应该是内部加了一个循环的if判断(mutex 互斥体; 互斥; 互斥锁)
if (pthread_mutex_init(&lock, NULL) != 0)
printf("mutex init has failed\\n");
exit(1);
// 2. Setup information about client and server
// 2. 设置client和server的信息
printf("2. Setup information about client and server\\n");
// 前面加struct是因为告诉你sockaddr_in是个结构体类,不加也可以,可能不同编译器有不同的行为,可以加上
struct sockaddr_in nwClientAddr, nwServerAddr;
//为nwServerAddr分配内存
memset(&nwServerAddr, 0, sizeof(nwServerAddr));
// 3. IP address should be IPv4
// 设置IP address时应该为Ipv4格式,Ipv6不支持
nwServerAddr.sin_family = AF_INET;
nwServerAddr.sin_addr.s_addr = htonl(INADDR_ANY);
nwServerAddr.sin_port = htons(SERVER_PORT);
// 4. Bind to Server Address
// 4. 绑定(设置)sockfd的地址
if (bind(sockfd, (const struct sockaddr *) &nwServerAddr, sizeof(nwServerAddr)) == -1)
perror("Unable to Bind");
exit(1);
// 5. Listen Socket for incoming File
// 5. sockfd对传递过来的消息,进行监听,这里LISTEN_PORT有些定义有些问题,实际应该为backlog,它是建立好连接处于ESTABLISHED状态的队列的长度。参考文章:https://blog.csdn.net/u022812849/article/details/109737020
printf("5. Listen Socket for incoming File\\n");
if (listen(sockfd, LISTEN_PORT) == -1)
perror("Error in Socket Listening");
exit(1);
// 6. Accept connection for concurrency number
// 接受来自多个客户端(client)的同时(concurrency)连接
printf("6. Accept connection for concurrency number\\n");
socklen_t adlen = sizeof(nwClientAddr);
// 这里会阻塞,直到有client进行连接,详细理解见https://blog.csdn.net/tjcwt2011/article/details/122142072,同一地址的多个client可以连接sockfd
int cfd = accept(sockfd, (struct sockaddr *) &nwClientAddr, &adlen);
if (cfd == -1)
perror("Error in Accepting Connection for ");
exit(1);
int val = 0;
//这里加锁了,只能有一个线程继续进行下面的操作,其余的被挡在上面的函数地址,即(int val = 0;)处
pthread_mutex_lock(&lock);
char conString[MAX_NAME] = 0;
//这里会返回要传多少个文件到服务器,recv是接收client返回的信息
if (recv(cfd, conString, MAX_NAME,0) == -1)
perror("Unable to receive concurrency due to connection or file error");
exit(1);
char *numstr = basename(conString);
val = atoi(numstr);
printf("Number of files to receive: %d\\n", val);
//断开客户端cfd的连接
close(cfd);
pthread_mutex_unlock(&lock);
int *new_sock;
pthread_t tid[60];
int idx = 0;
while(1)
// 7. Accept connection for creating multi-thread
printf("7. Accept connection for creating multi-thread\\n");
//这里要结合客户端代码来理解,客户端根据要传递的文件数量,会建立和文件数量相同的client,每个client有独立的线程发送数据
socklen_t addrlen = sizeof(nwClientAddr);
int connfd = accept(sockfd, (struct sockaddr *) &nwClientAddr, &addrlen);
if (connfd == -1)
perror("Error in Accepting Connection");
exit(1);
new_sock = (int*)malloc(1);
*new_sock = connfd;
//printf("Connection ID: %d\\n", *new_sock);
// 8. Multi-Thread creation
// 创建新的线程来接收client发送的数据,所有线程都会调用socketThreadFT函数,所以socketThreadFT函数里有线程锁mutex,来阻塞多线程的行为。
printf("8. Multi-Thread creation\\n");
if(pthread_create(&tid[idx], NULL, socketThreadFT, (void*)new_sock) < 0 )
printf("Failed to create thread\\n");
exit(1);
idx++;
close(sockfd);
pthread_mutex_destroy(&lock);
return 0;
以上是关于ubuntu16.04 socket传输文件的主要内容,如果未能解决你的问题,请参考以下文章