|
发表于 2005-11-11 17:13:03
|
显示全部楼层
有那么复杂么!刚好有个例子,你自己研究研究吧。
服务端:
[code:1]
#include <stdio.h>
#include <fcntl.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#define BUF_SIZE 0x100000
main()
{
int sock,fd,client_sockfd;
int ret;
struct sockaddr_in address;
unsigned char *buf;
buf = malloc(BUF_SIZE);
if(!buf)
return;
unlink("file.recv");
fd = open("file.recv",O_RDWR | O_CREAT | O_TRUNC,0644);
if(!fd)
{
free(buf);
return;
}
sock=socket(AF_INET,SOCK_STREAM,0);
address.sin_family = AF_INET;
address.sin_addr.s_addr = htonl (INADDR_ANY);
address.sin_port = htons (1234);
bind(sock,(struct sockaddr *) &address,sizeof(address));
listen(sock,8);
client_sockfd = accept(sock, NULL,NULL);
do{
ret = read(client_sockfd,buf,BUF_SIZE);
write(fd,buf,ret);
}while(ret);
close(client_sockfd);
close(sock);
free(buf);
}
[/code:1]
客户端:
[code:1]
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#define BUF_SIZE 0x100000
main(int argc,char **argv)
{
int sock,fd;
struct sockaddr_in address;
unsigned char *buf;
int ret;
if(argc != 2)
return;
buf = malloc(BUF_SIZE);
if(!buf)
return;
fd = open(argv[1],O_RDONLY);
if(!fd)
{
free(buf);
return;
}
address.sin_family = AF_INET;
address.sin_addr.s_addr = inet_addr("127.0.0.1");
address.sin_port = htons(1234);
sock = socket(AF_INET,SOCK_STREAM,0);
if(sock)
{
ret = connect(sock,(struct sockaddr *)&address,sizeof(address));
if(ret >= 0)
{
while(ret=read(fd,buf,BUF_SIZE))
write(sock,buf,ret);
}
}
close(fd);
close(sock);
free(buf);
}
[/code:1]
gcc server.c -o server
gcc client.c -o client
./server
./client 要传输的文件 |
|