Transferring file using sockets from C++ application to Java application -


i'm trying transfer file using sockets c++ application java application. wrote simple code in c++ send file:

int main() {     int sock;     struct sockaddr_in sa;     char* memblock;      /* create socket on send. */     sock = socket(pf_inet, sock_dgram, ipproto_udp);     if (sock < 0) {         printf("opening datagram socket");         exit(1);     }      /* construct name of socket send to. */     sa.sin_family = af_inet;     sa.sin_addr.s_addr = htonl(0x7f000001);     sa.sin_port = htons(4444);      /* send messages. */     file *file;     unsigned long filelength = 0;      file = fopen(file_path, "rb");     if (!file) {         printf("error opening file.\n");         return 1;     }      // file length.     fseek(file, 0, seek_end);     filelength = ftell(file);     printf("file length is: %d.\n", filelength);     fseek(file, 0, seek_set);      memblock = (char*)malloc(sizeof(char)*filelength);     if (memblock == null) {fputs ("memory error",stderr); exit(2);}      // copy file buffer:     int result = fread(memblock, 1, filelength, file);     if (result != filelength) {fputs ("reading error", stderr); exit(3);}      int pos = 0;     char* pmemblock = memblock;     while (pos < filelength) {         int sent = sendto(sock, pmemblock, 80, 0, (struct sockaddr*)&sa, sizeof sa);         if (sent < 0)             printf("error sending datagram message.\n");         else printf("sent %d.\n", sent);         pos += 80;         pmemblock += 80;     }      delete memblock;     fclose(file);      close(sock);     return 0; } 

on java side how write down data received:

while (true) {                 receivedata = new byte[300];                 receivedpacket = new datagrampacket(receivedata, receivedata.length);                 serversocket.receive(receivedpacket);                 try {                     fou = new fileoutputstream(<filename>, true);                 } catch (filenotfoundexception e1) {                     e1.printstacktrace();                 }                 fou.write(receivedpacket.getdata(), 0, 80);                 fou.close();             } 

the result file receive correct point, not complete. there wrong in code wither in java or in c++ part? thanks!

  • udp doesn't guarantee datagrams arrive.
  • udp doesn't guarantee datagrams arrive once.
  • udp doesn't guarantee datagrams arrive in sequence sent them.

see here.

you wrong assume these rules not apply because sender , receiver on same machine.

udp without form of additional reliability , sequencing wrong choice want do.

you should use tcp (or reliable transport) rather udp.


Comments

Popular posts from this blog

linux - Mailx and Gmail nss config dir -

c# - Is it possible to remove an existing registration from Autofac container builder? -

php - Mysql PK and FK char(36) vs int(10) -