98.TCP通信传输文件

时间:2022-07-24 16:05:02

客户端

 #define  _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include <stdlib.h>
#include <string.h>
//网络通信
#include<winsock.h>
#pragma comment(lib,"ws2_32.lib") void main()
{
//发送的消息
char sendbuf[] = { };
//收到的消息
char receivebuf[] = { };
//发送的长度
int sendlength = ;
//接收的长度
int receivelength = ; //通信套接字,用于创建TCP连接
SOCKET socket_send;
//创建服务器端结构体保存ip地址以及端口号
SOCKADDR_IN sever_addr; //版本,2,2版本
WORD wversion = MAKEWORD(, );
//版本
WSADATA wsadata;
//获取版本对比,开始通信
int error = WSAStartup(wversion, &wsadata);
if (error != )
{
printf("error");
return;
}
//取出低八位,高八位,对比版本
if (LOBYTE(wsadata.wVersion) != || HIBYTE(wsadata.wVersion) != )
{
printf(" version error");
return;
}
//设置通信模式
sever_addr.sin_family = AF_INET;
sever_addr.sin_addr.S_un.S_addr = inet_addr("192.168.0.104");
//端口
sever_addr.sin_port = htons(); //创建tcp通信
socket_send = socket(AF_INET, SOCK_STREAM, ); //通过套接字连接到服务器
connect(socket_send, (SOCKADDR*)&sever_addr, sizeof(SOCKADDR)); FILE *pfr = fopen("1.txt", "rb"); while (!feof(pfr))
{
fgets(sendbuf, , pfr);
//通过套接字发送到服务器
sendlength = send(socket_send, sendbuf, , );
memset(receivebuf, , );//清零
} //关闭网络
closesocket(socket_send);
WSACleanup();//关闭
system("pause");
}

服务器端

 #define  _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include <stdlib.h>
#include <string.h>
//网络通信
#include<winsock.h>
#pragma comment(lib,"ws2_32.lib") void main()
{
//发送的消息
char sendbuf[] = { };
//收到的消息
char receivebuf[] = { };
//发送的长度
int sendlength = ;
//收到的长度
int receivelength = ;
// SOCKADDR结构体长度
int length; //服务器套接字
SOCKET socket_server;
//连接的套接字
SOCKET sorket_receive; //服务器结构体信息
SOCKADDR_IN sever_addr;
//客户端结构体信息
SOCKADDR_IN client_addr; //版本,2,2版本
WORD wversion = MAKEWORD(, );
//当前版本
WSADATA wsadata;
//获取版本对比,开始通信
int error = WSAStartup(wversion, &wsadata);
if (error != )
{
printf("error");
return;
}
//取出低八位,高八位,对比版本
if (LOBYTE(wsadata.wVersion) != || HIBYTE(wsadata.wVersion) != )
{
printf(" version error");
return;
} //设置服务器结构体信息
sever_addr.sin_family = AF_INET;//通信
sever_addr.sin_addr.S_un.S_addr = htonl(INADDR_ANY);//获取本地址
sever_addr.sin_port = htons();//端口 //创建服务器套接字,接受消息 SOCK_STREAM流
socket_server = socket(AF_INET, SOCK_STREAM, );//创建
//把套接字与服务器结构体绑定 (绑定的是地址,端口)
bind(socket_server, (SOCKADDR*)&sever_addr, sizeof(SOCKADDR));
//服务器套接字监听
listen(socket_server, );//最大等待数目为5
length = sizeof(SOCKADDR);
//通过服务器套接字接受连接,初始化套接字sorket_receive,把连接者的信息存放在结构体client_addr中
sorket_receive = accept(socket_server, (SOCKADDR*)&client_addr, &length); FILE *pfw = fopen("2.txt", "wb");
int flag = ;//判断是否文件传输完
while ()
{
//接收数据
receivelength = recv(sorket_receive, receivebuf, , );
if (strlen(receivebuf) > )
{
flag = ;
printf("客户端说:%s\n", receivebuf);
fputs(receivebuf, pfw);
memset(receivebuf, , );//清零
}
else
{
if (flag == )
{
printf("传输完成\n");
break;
}
}
} //释放网络
closesocket(sorket_receive);//关闭网络
closesocket(socket_server);
WSACleanup();//关闭
system("pause");
}