利用流式套接字实现文件传输

本文介绍了如何利用TCP流式套接字在服务器端和客户端之间实现文件的传输。通过示例代码展示了服务器端的实现过程,详细讲解了套接字编程的关键步骤,包括连接建立、数据传输和连接关闭。
摘要由CSDN通过智能技术生成

Server端代码:


#include "stdafx.h"  
#include <winsock2.h>  
#include <cstdio>
#include <wincrypt.h>
#include <time.h>
#include <cstring>
#include <iostream>  
#include <string.h> 
#define PORT 2345
#pragma comment(lib, "user32.lib")
#pragma comment(lib, "shlwapi.lib")
#pragma comment(lib, "ws2_32.lib")   
#pragma comment(lib, "crypt32.lib")  

using namespace std;
const int MAX1=1000;
typedef long long LL;
typedef unsigned long long ULL;

int recvn(SOCKET s, char * recvbuf, unsigned int fixedlen)
{
	int iResult; 
	int cnt=fixedlen; //剩余多少字节尚未接收 
	while ( cnt > 0 ) 
	{
		iResult = recv(s, recvbuf, cnt, 0);
		if ( iResult < 0 )
		{
			printf("error: %d\n", WSAGetLastError());
			return -1;
		}
		if ( iResult == 0 )//对方关闭连接,返回已接收到的小于fixedlen的字节数 
			return fixedlen - cnt;
		recvbuf +=iResult;
		cnt -=iResult;
	}
	return fixedlen;
}

int recvvl(SOCKET s) 
{ 
	int iResult;
	unsigned int reclen; //用于存储报文头部存储的长度信息 
	unsigned int recvbuflen=0;
	char filename[100];	
	TCHAR name[100];
	char tmp[1000],recvbuf[1000];
	memset(tmp,0,sizeof(tmp));
	int i=0;
	memset(filename,0,sizeof(filename));
	while(true)
	{
		iResult = recvn(s, tmp, sizeof( char )); 
		if(tmp[0]=='#') break;
		filename[i++]=tmp[0];
		if ( iResult !=sizeof (char ))//没有成功接收到一个整型数据
		{ 
			if ( iResult == -1 ) 
			{
				printf("get the filename error: %d\n", WSAGetLastError());
				return -1; 
			} 
			else 
			{
				printf("connect closed when get the filename\n");
				return 0;
			}
		}
	}
	cout<<"fil
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值