LinuxSir.cn,穿越时空的Linuxsir!

 找回密码
 注册
搜索
热搜: shell linux mysql
12
返回列表 发新帖
楼主: linuxgrin

请问如何利用SOCKET实现文件的传输?

[复制链接]
发表于 2006-1-22 09:13:09 | 显示全部楼层
下面是一个你要的类似的code, 但是他是从server 读取stream, 然后放在buffer里面。你做一些改动就给可以用来传输文件了, 我想你是做client的吧, 你要是想做server code, 还需要multithreads。

你不是要做命令行吗? 其实我觉得你最好去看看wget 的代码, 你就全会了
去linux 下载wget,  man wget 去看看它的menu. 然后下载它的源代码。。。 是不是很简单?


#include <stdio.h>
#include <string.h>
#include <netdb.h>
#include <linux/in.h>
#include <sys/socket.h>
#include <unistd.h>


#define buflen 512  // define 缓冲区的size
unsigned int portno = 3333; // 端口 自己改你试用的
char hostname[] = "192.168.100.2"; // host IP address

char *buf[buflen];     /* declare global to avoid stack */

void dia(char *sz) { printf("Dia %s\n", sz); }



// 自己读代码, 有些代码这里不需要, 要是不会的话。。。赫赫,你把任务放在这大家帮你写
int printFromSocket(int sd, char *buf)
  {
  int len = buflen+1;
  int continueflag=1;
  while((len >= buflen)&&(continueflag)) /* quit b4 U read an empty socket */
    {
    len = read(sd, buf, buflen);
    write(1,buf,len);
    buf[buflen-1]='\0';  /* Note bug if "Finished" ends the buffer */   
   
    continueflag=(strstr(buf, "Finished")==NULL); /* terminate if server says "Finished" */  //这个你不// 学要
    }     
  return(continueflag);
  }


main()
   {
   int sd = socket(AF_INET, SOCK_STREAM, 0);  /* init socket descriptor */
   struct sockaddr_in sin;
   struct hostent *host = gethostbyname(hostname);
   char buf[buflen];
   int len;

   /*** PLACE DATA IN sockaddr_in struct ***/
   memcpy(&sin.sin_addr.s_addr, host->h_addr, host->h_length);
   sin.sin_family = AF_INET;
   sin.sin_port = htons(portno);

   /*** CONNECT SOCKET TO THE SERVICE DESCRIBED BY sockaddr_in struct ***/
   if (connect(sd, (struct sockaddr *)&sin, sizeof(sin)) < 0)
     {
     perror("connecting");
     exit(1);
     }

   sleep(1);   /* give server time to reply */
   while(1)
     {
     printf("\n\n");
     if(!printFromSocket(sd, buf)) break;
     fgets(buf, buflen, stdin);   /* remember, fgets appends the newline */
     write(sd, buf, strlen(buf));
     sleep(1);               /* give server time to reply */
     }
   close(sd);
   }
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则

快速回复 返回顶部 返回列表