//简单文件传输程序的服务器端程序。
#include "stdio.h"
#include "winsock.h"
#define PORT 6543 /*定义监听端口号。*/
#pragma comment(lib,"ws2_32.lib")
int main()
{
SOCKET sock_server; /*定义网络连接的相关的变量。*/
struct sockaddr_in addr,client_addr;
int addr_len = sizeof(struct sockaddr_in);
SOCKET newsock;
//初始化winsock DLL
WORD wVersionRequested;
WSADATA wsaData;
wVersionRequested=MAKEWORD(1,1); //生成版本号1.1
if(WSAStartup(wVersionRequested,&wsaData)!=0)
{
printf("没有找到合适的winsock.dll!\n");
return 0;
}
//创建套接字
if ((sock_server = socket(AF_INET,SOCK_STREAM,0))<0) /*建立一个socket。*/
{
printf("创建套接字失败!\n");
return 0;
}
else
{
printf("socket created .\n"); /*socket建立成功。*/
printf("socked id: %d \n",sock_server);
}
//绑定IP端口
memset((void *)&addr,0,addr_len);
addr.sin_family =AF_INET;
addr.sin_port = htons(PORT);
addr.sin_addr.s_addr = htonl(INADDR_ANY);//允许套接字使用分配给本机的任何IP
if(bind(sock_server,(LPSOCKADDR)&addr,sizeof(addr))!=0)
{
printf("邦定失败!\n");
closesocket(sock_server);
WSACleanup();
return 0;
}
else
{
printf("邦定成功!\n服务器端口:%d\n",PORT) ;
}
//监听端口。
if(listen(sock_server,5)!=0)
{
printf("listen函数调用失败!\n");
closesocket(sock_server);
WSACleanup();
return 0;
}
else
{
printf("listenning......\n");
}
//接收客户连接请求
if((newsock = accept(sock_server,(LPSOCKADDR)&client_addr,&addr_len))==INVALID_SOCKET)
{
printf("accept函数调用失败!\n");
closesocket(sock_server);
WSACleanup();
return 0;
}
printf("cnnect from %s\n",inet_ntoa(client_addr.sin_addr)); /*输出k客户机地址。*/
//定义文件传输所需变量
char filename[256]="c:\\aaa.TXT";//要传输的文件的文件名
FILE *fp;
char OrderBuffer[50], fileBuffer[1000];
int size;
if((fp=fopen(filename,"rb"))==NULL)//以二进制读方式打开要传输的文件
{
printf("Cannot open %s\n",filename);
strcpy(filename,"<Nofile>"); //打开不成功时发送给客户端的信息
send(newsock,filename,sizeof(filename),0); //给客户端发送打开文件不成功信息
closesocket(newsock); /*关闭socket。*/
closesocket(sock_server);
WSACleanup();
return 0;
}
else
send(newsock,filename,sizeof(filename),0); //文件打开成功则给对方发送文件名
if(recv(newsock,OrderBuffer,sizeof(OrderBuffer),0)<=0) //接收对方发送来的文件接收准备好信息。
{
printf("接受命令失败\n");
closesocket(newsock);
closesocket(sock_server);
WSACleanup();
return 0;
}
//如果对方准备好接收则发送文件
if(strcmp(OrderBuffer,"OK")==0)
{
while(!feof(fp))
{
size=fread(fileBuffer,1,sizeof(fileBuffer),fp);
send(newsock,fileBuffer,size,0);
}
printf("file transfer finished");//显示传输完成
fclose(fp);//关闭文件
}
//传输完成
closesocket(newsock);
closesocket(sock_server);
WSACleanup();
return 0;
}