使用UDP& amp;的客户端 - 服务器文本文件传输在C ++中的套接字,服务器创建一个空白文件

时间:2013-05-07 01:32:19

标签: c++ sockets udp file-transfer

首先,我想指出我不是一个优秀的程序员,所以请耐心等待我。程序中的逻辑如下:客户端向服务器发送文本文件,服务器以不同的名称保存它。简而言之,与此主题非常相似: “File transfer server/client using socket”除了我使用不同的协议。我想我已成功发送文件,但它似乎是服务器,在创建一个空白文件后,卡在一个循环/不写入任何内容。

以下是客户端的代码:

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h> /* memset() */
#include <sys/time.h> /* select() */ 
#include <errno.h>
#include <sys/stat.h>
#include <fcntl.h>  


#define REMOTE_SERVER_PORT 1500
#define MAX_MSG 100
#define PLIK    "/home/aatami/Documents/programowanie/serwer/plik.txt"
#define LENGTH 512
int main(int argc, char *argv[]) {

  int sd, rc, i,fd;
  unsigned int cliLen;
  struct sockaddr_in cliAddr, remoteServAddr;
  struct hostent *h;
  char  buf[LENGTH];
  /* check command line args */
  if(argc<3) {
    printf("usage : %s <server> <data1> ... <dataN> \n", argv[0]);
    exit(1);
  }

  /* get server IP address (no check if input is IP address or DNS name */
  h = gethostbyname(argv[1]);
  if(h==NULL) {
    printf("%s: unknown host '%s' \n", argv[0], argv[1]);
    exit(1);
  }

  printf("%s: sending data to '%s' (IP : %s) \n", argv[0], h->h_name,
     inet_ntoa(*(struct in_addr *)h->h_addr_list[0]));

  remoteServAddr.sin_family = h->h_addrtype;
  memcpy((char *) &remoteServAddr.sin_addr.s_addr, 
     h->h_addr_list[0], h->h_length);
  remoteServAddr.sin_port = htons(REMOTE_SERVER_PORT);

  /* socket creation */
  sd = socket(AF_INET,SOCK_DGRAM,0);  /* port 0 - system gets the first free one */ 
  if(sd<0) {
    printf("%s: cannot open socket \n",argv[0]);
    exit(1);
  }

  /* bind any port */
  cliAddr.sin_family = AF_INET;
  cliAddr.sin_addr.s_addr = htonl(INADDR_ANY);
  cliAddr.sin_port = htons(0);

  rc = bind(sd, (struct sockaddr *) &cliAddr, sizeof(cliAddr));
  if(rc<0) {
    printf("%s: cannot bind port\n", argv[0]);
    exit(1);
  }


  /* send data */
  for(i=2;i<argc;i++) {
    rc = sendto(sd, argv[i], strlen(argv[i])+1, 0, 
        (struct sockaddr *) &remoteServAddr, 
        sizeof(remoteServAddr));

    if(rc<0) {
      printf("%s: cannot send data %d \n",argv[0],i-1);
      close(sd);
      exit(1);
    }
    /* send text file */


        char sdbuf[LENGTH]; 
        printf("[Client] Sending %s to the Server... ", PLIK);
        FILE *fs = fopen(PLIK, "r");
        if(fs == NULL)
        {
            printf("ERROR: File %s not found.\n", PLIK);
            exit(1);
        }

        bzero(sdbuf, LENGTH); 
        int fs_block_sz; 
        while((fs_block_sz = fread(sdbuf, sizeof(char), LENGTH, fs)) > 0)
        {
            if(send(sd, sdbuf, fs_block_sz, 0) < 0)
            {
                fprintf(stderr, "ERROR: Failed to send file %s. (errno = %d)\n", PLIK,           errno);
                break;
            }
            bzero(sdbuf, LENGTH);
        }
        printf("Ok File %s from Client was Sent!\n", PLIK);


  }

  return 1;

}

服务器的代码:

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h> /* close() */
#include <string.h> /* memset() */
#include <errno.h>
#define LENGTH 512
#define LOCAL_SERVER_PORT 1500
#define MAX_MSG 100
#define PLIKSERV    "/home/aatami/Documents/programowanie/serwer/plikserv.txt"
int main(int argc, char *argv[]) { /* licznik argumentow, tablica argumentow */

  int sd, rc,nsockfd;
  unsigned int n,cliLen;
  struct sockaddr_in cliAddr, servAddr;
  char msg[MAX_MSG];
   char  buf[512],sbuf[LENGTH];
  /* socket creation */
  sd=socket(AF_INET, SOCK_DGRAM, 0);
  if(sd<0) {
    printf("%s: cannot open socket \n",argv[0]);
    exit(1);
  }

  /* bind local server port */
  servAddr.sin_family = AF_INET;
  servAddr.sin_addr.s_addr = htonl(INADDR_ANY);
  servAddr.sin_port = htons(LOCAL_SERVER_PORT);
  rc = bind (sd, (struct sockaddr *) &servAddr,sizeof(servAddr));
  if(rc<0) {
    printf("%s: cannot bind port number %d \n", 
       argv[0], LOCAL_SERVER_PORT);
    exit(1);
  }

  printf("%s: waiting for data on port UDP %u\n", 
       argv[0],LOCAL_SERVER_PORT);



  /* server infinite loop */
  while(1) {

    /* init buffer */
    memset(msg,0x0,MAX_MSG);


    /* receive message */
    cliLen = sizeof(cliAddr);
    n = recvfrom(sd, msg, MAX_MSG, 0, 
         (struct sockaddr *) &cliAddr, &cliLen);

    if(n<0) {
      printf("%s: cannot receive data \n",argv[0]);
      continue;
    }

    /* print received message */
    printf("%s: from %s:UDP%u : %s \n", 
       argv[0],inet_ntoa(cliAddr.sin_addr),
       ntohs(cliAddr.sin_port),msg);

         unsigned int sin_size = sizeof(struct sockaddr_in);




        FILE *fr = fopen(PLIKSERV, "a");
        if(fr == NULL)
            printf("File %s Cannot be opened file on server.\n", PLIKSERV);
        else
        {
            bzero(sbuf, LENGTH); 
            int fr_block_sz = 0;
            while((fr_block_sz = recvfrom(sd, buf, LENGTH, 0,(struct sockaddr *) &cliAddr, &cliLen)) > 0) 
            {
                int write_sz = fwrite(buf, sizeof(char), fr_block_sz, fr);
                if(write_sz < fr_block_sz)
                {
                    perror("File write failed on server.\n");
                }
                bzero(buf, LENGTH);
                if (fr_block_sz == 0 || fr_block_sz != 512) 
                {
                    break;
                }
            }
            if(fr_block_sz < 0)
            {
                if (errno == EAGAIN)
                {
                    printf("recv() timed out.\n");
                }
                else
                {
                    fprintf(stderr, "recv() failed due to errno = %d\n", errno);
                    exit(1);
                    }
                }
            printf("Ok received from client!\n");
            fclose(fr); 
        }

  }/* end of server infinite loop */

return 0;

}

任何帮助都非常感谢!

1 个答案:

答案 0 :(得分:1)

看到你的代码之后,我建议尝试从客户端向服务器发送“Hello world \ n”,看看你是否在那里。在客户端和服务器之间建立连接后,尝试扩展代码以进行文件传输。

但请记住UDP:

“UDP使用简单的传输模型,协议机制最少。它没有握手对话,因此将底层网络协议的任何不可靠性暴露给用户的程序。因为这通常是IP不可靠的媒体,所以没有保证交付,订购或重复保护。如果在网络接口级别需要纠错功能,应用程序可以使用为此目的设计的传输控制协议(TCP)。“

当你启动客户端时,它会尽可能快地发送所有数据包,可能是数据包在服务器站点丢失或混乱甚至重复。我还建议等待数据包以确认正确的接收。我的意思是,当服务器收到数据包时,它会发送一个数据包以向客户端确认。通过这种方式,可以保持对话(对话)并完成转移。