标签:
首先是两个程序,分别是socket的客户端和服务端。(在windows系统vc6.0编译)
服务器端:
#include <Winsock2.h>
#include <stdio.h>
#pragma comment(lib,"WS2_32.lib")
void main()
{
WSADATA wsd;
SOCKET server; //服务器socket
SOCKADDR_IN addrSrv;
char sendBuf[100];
char recvBuf[100];
SOCKADDR_IN addrClient;
SOCKET client; //连接的客户端socket
int len;
if(WSAStartup(MAKEWORD(2,2),&wsd)!=0)
{
printf("start up failed!\n");
return ;
}
server=socket(AF_INET,SOCK_STREAM,0); //创建socket
addrSrv.sin_addr.S_un.S_addr=htonl(INADDR_ANY); //设置地址
addrSrv.sin_family=AF_INET;
addrSrv.sin_port=htons(6000); //设置端口号
bind(server,(SOCKADDR*)&addrSrv,sizeof(SOCKADDR)); //绑定
listen(server,5); //设置最多连接数
len=sizeof(SOCKADDR);
while(1)
{
client=accept(server,(SOCKADDR*)&addrClient,&len); //接收客户端连接
sprintf(sendBuf,"Welcome %s ",
inet_ntoa(addrClient.sin_addr));
send(client,sendBuf,strlen(sendBuf)+1,0); //发送信息客户端
recv(client,recvBuf,100,0); //接收客户端数据
printf("%s\n",recvBuf);
closesocket(client);
}
closesocket(client); //关闭连接
WSACleanup();
}
客户端:
#include <winsock2.h>
#include <stdio.h>
#pragma comment(lib,"WS2_32.lib")
void main()
{
WSADATA wsd;
SOCKET sockClient; //客户端socket
SOCKADDR_IN addrSrv;
char recvBuf[100];
if(WSAStartup(MAKEWORD(2,2),&wsd)!=0)
{
printf("start up failed!\n");
return ;
}
sockClient=socket(AF_INET,SOCK_STREAM,0); //创建socket
addrSrv.sin_addr.S_un.S_addr=inet_addr("127.0.0.1");
addrSrv.sin_family=AF_INET;
addrSrv.sin_port=htons(6000);
connect(sockClient,(SOCKADDR*)&addrSrv,sizeof(SOCKADDR)); //连接服务器端
recv(sockClient,recvBuf,100,0); //接收服务器端数据
printf("%s\n",recvBuf);
send(sockClient,"hello world",strlen("hello world")+1,0); //向服务器端发送数据
closesocket(sockClient); //关闭连接
WSACleanup();
}
以上两个程序只需要简单的改写,就可以实现简单的传送文件了。
将客户端发送的信息改为发送请求的文件名。
send(sockClient,filename,strlen(filename)+1,0);
服务器端接收到文件名:
recv(client,filename,100,0);
服务器端发送文件信息:
if((fp=fopen(filename,"rb"))==NULL)closesocket(client); //请求的文件不存在,则关闭连接
n=fread(sendBuf,1,100,fp);
while(n>0){
send(client,sendBuf,n,0); //发送文件客户端
n=fread(sendBuf,1,100,fp);
}
客户端则接收文件信息:
if((fp=fopen(filename,"wb"))==NULL)
{
return ;
}
while((ret=recv(sockClient,recvBuf,100,0))>0)
{
fwrite(recvBuf,1,ret,fp);
}
标签:
原文地址:http://www.cnblogs.com/cyzn/p/5714511.html