tcp实现图片传送c语言
时间: 2024-01-20 16:40:56 浏览: 90
C实现TCP传照片
TCP协议本身并不支持图像传输,但可以通过将图像数据拆分为较小的数据包并将其传输到接收方,然后在接收方重新组装图像数据。以下是一个简单的C语言TCP图像传输的示例代码:
发送方:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <fcntl.h>
#define SERVER_IP "127.0.0.1"
#define SERVER_PORT 8000
#define FILE_NAME "test.jpg"
#define BUFFER_SIZE 1024
int main()
{
//创建socket
int sockfd;
if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
{
perror("socket");
exit(1);
}
//设置服务器地址信息
struct sockaddr_in server_addr;
memset(&server_addr, 0, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(SERVER_PORT);
server_addr.sin_addr.s_addr = inet_addr(SERVER_IP);
//建立连接
if(connect(sockfd, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0)
{
perror("connect");
exit(1);
}
//打开要发送的文件
int fd = open(FILE_NAME, O_RDONLY);
if(fd < 0)
{
perror("open");
exit(1);
}
//循环发送文件数据
char buffer[BUFFER_SIZE];
int len;
while((len = read(fd, buffer, BUFFER_SIZE)) > 0)
{
if(send(sockfd, buffer, len, 0) < 0)
{
perror("send");
exit(1);
}
}
//关闭文件和socket
close(fd);
close(sockfd);
return 0;
}
```
接收方:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <fcntl.h>
#define SERVER_IP "127.0.0.1"
#define SERVER_PORT 8000
#define SAVE_FILE_NAME "recv.jpg"
#define BUFFER_SIZE 1024
int main()
{
//创建socket
int sockfd;
if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
{
perror("socket");
exit(1);
}
//设置服务器地址信息
struct sockaddr_in server_addr;
memset(&server_addr, 0, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(SERVER_PORT);
server_addr.sin_addr.s_addr = inet_addr(SERVER_IP);
//绑定地址和端口号
if(bind(sockfd, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0)
{
perror("bind");
exit(1);
}
//监听连接
if(listen(sockfd, 5) < 0)
{
perror("listen");
exit(1);
}
//接收连接
int clientfd;
struct sockaddr_in client_addr;
socklen_t addrlen = sizeof(client_addr);
if((clientfd = accept(sockfd, (struct sockaddr *)&client_addr, &addrlen)) < 0)
{
perror("accept");
exit(1);
}
//打开要保存的文件
int fd = open(SAVE_FILE_NAME, O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP);
if(fd < 0)
{
perror("open");
exit(1);
}
//循环接收文件数据
char buffer[BUFFER_SIZE];
int len;
while((len = recv(clientfd, buffer, BUFFER_SIZE, 0)) > 0)
{
if(write(fd, buffer, len) < 0)
{
perror("write");
exit(1);
}
}
//关闭文件和socket
close(fd);
close(clientfd);
close(sockfd);
return 0;
}
```
阅读全文