简体   繁体   English

如何通过tcp/ip从java接收文件到C?

[英]How to receive a file from java to C via tcp/ip?

I have to send a file to java, and java has to receive the file and send it back to C via tcp/ip.我必须向java发送一个文件,java必须接收该文件并通过tcp/ip将其发送回C。 I am able to send the file but in receiving i am not able to receive any data.我可以发送文件,但在接收时我无法接收任何数据。 I am giving the code for reference.我提供代码以供参考。

int send_text(int socket)
{
    FILE *text;
    char a[50];
    int size, read_size, stat, packet_index;
    char send_buffer[8008], read_buffer[8008];
    int wrt = 0, sock_fd, tsize = 0;
    packet_index = 1;
    int i = 0;
    text = fopen("/home/sosdt009/Desktop/character3.txt", "r");
    if (text == NULL)
    {
        printf("Error Opening text File:");
        exit(-1);
    }

    printf("Getting text Size:\n");
    gets(a);
    fseek(text, 0, SEEK_END);
    size = ftell(text);
    fseek(text, 0, SEEK_SET);
    printf("Total text size: %d \n", size);
    gets(a);

    //Send text Size
    printf("Sending text Size:\n");
    gets(a);
    send(socket, (void *) &size, sizeof(size), 0);
    while (size > tsize)
    {

        //Read from the file into our send buffer
        printf("Ready for sending:\n");
        gets(a);
        read_size = fread(send_buffer, 1, sizeof(send_buffer), text);
        printf("The size of send buffer:%c \n", sizeof(send_buffer));
        gets(a);
        printf("The read size value is :%d \n", read_size);
        gets(a);

        //Send data through our socket      
        for (i = 0; i < read_size; i++)
        {
            printf("Send value: %c \n", send_buffer[i]);
            gets(a);
        }

        do
        {
            stat = send(socket, send_buffer, read_size, 0);
            printf("The send size value is: %d \n", size);
            gets(a);
            printf("The read size value is: %d \n", read_size);
            gets(a);
        }
        while (stat < 0);

        printf("Packet %d, sent %d bytes.\n", packet_index, read_size);
        gets(a);

        //packet_index++;
        //Zero out our send buffer

        tsize = tsize + read_size;
        printf("The tsize value is:%d \n", tsize);
        gets(a);
        memset(send_buffer, 0, sizeof(send_buffer));

        if (read_size <= NULL)
        {
            printf("The connection is transferred to received text: \n");
            gets(a);
        }
    }

    fclose(text);
    printf("Text successfully send:\n");
    gets(a);

    return 0;
}

int receive_text(int socket)
{
    int buffersize, recv_size = 0, read_size = 1, write_size, size, stat;
    char *pBuf, a[50];
    int errno,i;
    FILE *text;
    text = fopen("/home/sosdt009/Desktop/receivednew.txt", "a");
    if (text == NULL)
    {
        printf("Error has occurred, text file could not be opened \n");
        return -1;
    }

    //Loop while we have not received the entire file yet
    while (read_size > 0)
    {
        ioctl(socket, FIONREAD, &buffersize);
        printf("The Buffersize is    :%d\n", buffersize);
        gets(a);
        printf("The size of socket is:%d\n", socket);
        gets(a);

        //We check to see if there is data to be read from the socket 
        if (buffersize > 0)
        {
            printf("Buffersize value is  :%d\n", buffersize);
            gets(a);
            pBuf = malloc(buffersize);
            if (!pBuf)
            {
                printf(errno, "Memory Error Cannot Allocate!\n");
                gets(a);
                exit(-1);
            }

            read_size = recv(socket, pBuf, buffersize, 0);
            printf("Read size value is :%d \n", read_size);
            gets(a);
            printf("Buffersize value is:%d \n", pBuf);
            gets(a);
            if (read_size < 0)
            {
                printf("%d\n", strerror(errno));
                printf("Data not written to the file:\n");
                gets(a);
                goto free;
            }

            //Write the currently read data into our text file
            write_size = fwrite(pBuf, 1, read_size, text);
            free(pBuf);
            printf("Write size value is   :%d \n", write_size);
            gets(a);
            printf("Buffer size value is  :%d \n", buffersize);
            gets(a);

            //Increment the total number of bytes read          
            recv_size += read_size;
            printf("Received size value is:%d \n", recv_size);
            gets(a);
            printf("Read size value is    :%d \n", read_size);
            gets(a);
        }
    }
    free: fclose(text);
    close(socket);
    printf("Text Successfully Received:\n");
    gets(a);

    return 0;
}

Adding the java code for further ref添加java代码以供进一步参考

  import java.io.File;
  import java.io.FileInputStream;
  import java.io.FileOutputStream;
  import java.io.IOException;
  import java.io.InputStream;
  import java.io.OutputStream;
  import java.net.ServerSocket;
  import java.net.Socket;
  public class Server1 {
  static ServerSocket serverSocket =null;
  private static Socket socket;
  public final static String FILE_TO_RECEIVED =   "/home/sosdt010/Desktop/Testfile/text2.txt";
  public final static int FILE_SIZE = 32092796 ;//4939993 ;//
  static int current=0;
  public static void main(String[] args) throws IOException,    InterruptedException {
  int port = 6777;
  serverSocket = new ServerSocket(port);
  System.out.println("Server Started and listening to the port 6777");
  socket = serverSocket.accept();
  InputStream is = socket.getInputStream();
  //ois=new ObjectInputStream(socket.getInputStream());
  //byte[] content = (byte[]) ois.readObject();
  FileOutputStream fos=new FileOutputStream(FILE_TO_RECEIVED );
  System.out.println(FILE_TO_RECEIVED);
  byte [] mybytearray  = new byte [FILE_SIZE];
  //  int bytesRead = is.read(mybytearray,0,mybytearray.length);
  // System.out.println(mybytearray.length);
  //current = bytesRead;
  //System.out.println(current+"/n"+bytesRead);
  int bytesRead;
   do {
         bytesRead =
         is.read(mybytearray, 0,mybytearray.length-current);

         if(bytesRead >= 0) current += bytesRead;
         System.out.println(bytesRead );

      } while(bytesRead > -1);
         for(int a=0;a<current;a++){
         fos.write(mybytearray[a]);
      }
          System.out.println(current +"new bytesread"+mybytearray.length);
      //fos.write(mybytearray, 0,current);
      System.out.println("Message received from server is "+current);


      OutputStream os=socket.getOutputStream();
      File myFile=new File(FILE_TO_RECEIVED);
      System.out.println(FILE_TO_RECEIVED);
      FileInputStream fis=new FileInputStream(myFile);
      byte[] mybytearray1=new byte[(int)myFile.length()];
      System.out.println(myFile.length());
      fis.read(mybytearray1, 0, mybytearray1.length);
      System.out.println("Bytes Read"+ mybytearray1.length);
      os.write(mybytearray1, 0, mybytearray1.length);
      System.out.println("Bytes write"+mybytearray1.length);
      System.out.println(mybytearray1.length);
      // byte[] content1 = Files.readAllBytes(new              File(FILE_TO_SEND).toPath());
      //oos.writeObject(content1);
       os.flush();

       fos.close();
       is.close();
       //fis.close();
       //os.close();
       socket.close();
    }
  }

I am giving the Receiving code that i am currently using in the program我正在提供我目前在程序中使用的接收代码

    int receive_text(int socket)
{ 
    int buffersize[8192],recv_size = 0,read_size = 1, write_size, size; 
    char *pBuf,a[50]; 
    int errno;
    FILE *text; 
    text = fopen("/home/sosdt009/Desktop/receivednew.txt", "w");    
    if (text == NULL)   
    {       
        printf("Error has occurred, text file could not be opened \n");
        return -1;
    }

     //Loop while we have not received the entire file yet

      while (read_size > 0)
     {          
        ioctl(socket, FIONREAD, &buffersize);
        printf("The Buffersize is    :%d\n",buffersize);
        gets(a);
        printf("The size of socket is:%d\n",socket);
        gets(a);

        //We check to see if there is data to be read from the socket 

    if (buffersize > 0)
    {
        printf("Buffersize value is  :%d\n", buffersize);
        gets(a);
        pBuf = malloc(buffersize);
        /*if (!pBuf)
        {
            printf(errno, "Memory Error Cannot Allocate!\n");
            gets(a);
            exit(-1);
        }*/
             while ((read_size = recv(socket, buffersize, sizeof(buffersize), 0)) > 0)
        {
            fwrite(pBuf, 1, read_size, text); // plus error handling ...
        }

        //read_size = recv(socket, pBuf, buffersize, 0);
        //printf("Read size value is :%d \n",read_size);
        //gets(a);
        //printf("Buffersize value is:%d \n",pBuf);
        //gets(a);

        if (read_size < 0)
        {
            printf("%d\n",strerror(errno));
            printf("Data not written to the file:\n");
            gets(a);
            goto free;
        }

        //Write the currently read data into our text file

        write_size = fwrite(pBuf,read_size,1,text); 
        free(pBuf);
        printf("Write size value is   :%d \n",write_size);
        gets(a);
        printf("Buffer size value is  :%d \n",buffersize);
        gets(a);

        //Increment the total number of bytes read

        recv_size += read_size;
        printf("Received size value is:%d \n",recv_size);
        gets(a);
        printf("Read size value is    :%d \n",read_size);       
        gets(a);            
      }
    }
     free:
     fclose(text);
     close(socket);     
     printf("Text Successfully Received:\n");
     gets(a);
     return 0;
 }

I am putting the code according to your modification我按照你的修改放代码

 int receive_text(int socket)
 { 
     int buffersize[8192],recv_size = 0,read_size=1, write_size, size; 
     char *pBuf,a[50]; 
     int errno;
     FILE *text; 
     text = fopen("/home/sosdt009/Desktop/receivednew.txt", "a");   
     if (text == NULL)  
     {      
         printf("Error has occurred, text file could not be opened \n");
         return -1;
     }

     //Loop while we have not received the entire file yet

      while (read_size > 0)
      {     
             while ((read_size = recv(socket, buffersize, sizeof(buffersize), 0)) > 0)
        {
            fwrite(pBuf, read_size, 1, text); // plus error handling ...
            printf("Write size value is   :%d \n",write_size);
            gets(a);
            printf("Buffer size value is  :%d \n",buffersize);
            gets(a);
        }
        //while (!buffersize && ioctl (socket,FIONREAD,&buffersize) >= 0)
            //ioctl(socket, FIONREAD, &buffersize);
        //printf("The Buffersize is  :%d\n",socket);
        //gets(a);

       //We check to see if there is data to be read from the socket 

       //if (buffersize > 0)
         //{
        //printf("Buffersize value is  :%d\n", buffersize);
        //gets(a);

        //pBuf = malloc(buffersize);
        if (!pBuf)
        {
            printf(errno, "Memory Error Cannot Allocate!\n");
            gets(a);
            exit(-1);
        }


        //read_size = recv(socket, pBuf, buffersize, 0);
        //printf("Read size value is :%d \n",read_size);
        //gets(a);
        //printf("Buffersize value is:%d \n",pBuf);
        //gets(a);

        if (read_size < 0)
        {
            printf("%d\n",strerror(errno));
            printf("Data not written to the file:\n");
            gets(a);
            goto free;
        }

        //Write the currently read data into our text file

        write_size = fwrite(pBuf,read_size,1,text); 
        free(pBuf);
        //

        //Increment the total number of bytes read

        recv_size += read_size;
        printf("Received size value is:%d \n",recv_size);
        gets(a);
        printf("Read size value is    :%d \n",read_size);       
        gets(a);            
    //}
     }
     free:
     fclose(text);
     close(socket);     
     printf("Text Successfully Received:\n");
     gets(a);
     return 0;
 }

This is very poor quality code.这是质量很差的代码。

Send loop:发送循环:

do
{
    stat = send(socket, send_buffer, read_size, 0);
    printf("The send size value is: %d \n", size);
    gets(a);
    printf("The read size value is: %d \n", read_size);
    gets(a);
} while (stat < 0); 
  • The 'send size value' is not size , it is stat “发送大小值”不是size ,它是stat
  • repeating this loop while there is an error is senseless.在出现错误时重复这个循环是没有意义的。
  • not repeating it while all the data hasn't been sent is also senseless, unless the socket is blocking and there have been no interrupts, which you aren't testing for.在所有数据尚未发送的情况下重复也是毫无意义的,除非套接字阻塞并且没有中断,您没有测试这些中断。 A more correct version would be:更正确的版本是:

     do { stat = send(socket, send_buffer, read_size, 0); printf("The send size value is: %d \\n", stat); if (stat > 0) { send_buffer += stat; read_size -= stat; } } while (stat < 0 && errno == EINTR);

Receive loop:接收循环:

while(read_size > 0)
{
    ioctl(socket, FIONREAD, &buffersize);
    printf("The Buffersize is    :%d\n",buffersize);

The buffersize is sizeof buffer at this point.此时sizeof buffersizeof buffer The *number of bytes available to be read without blocking is given by buffersize , *if and only if* ioctl()` returned zero.可在不阻塞的is given by读取的*字节数is given by buffersize is given by , *if and only if* ioctl()` 返回零。

    printf("The size of socket is:%d\n",socket);

There is no such thing as 'the size of the socket'.没有“插座的大小”这样的东西。 Remove.消除。

       // We check to see if there is data to be read from the socket 

Why?为什么? What else are you going to do?你还要做什么? Remove this entire test, and the ioctl() , and just block in recv() below.删除整个测试和ioctl() ,并在下面的recv()中阻止。

       if (buffersize > 0)
        {
           printf("Buffersize value is  :%d\n", buffersize);

You've already printed this.你已经打印了这个。 Remove.消除。

           pBuf = malloc(buffersize);

This is a waste of time and space.这是浪费时间和空间。 Use a fixed-size buffer and allocate it before the loop starts.使用固定大小的缓冲区并在循环开始之前分配它。 Remove this.去掉这个。

    read_size = recv(socket, pBuf, buffersize, 0);
    printf("Read size value is :%d \n",read_size);
    printf("Buffersize value is:%d \n",pBuf);

pBuf is not the 'buffersize value`, it is the address of the buffer, and printing it is pointless. pBuf不是'buffersize value',它是缓冲区的地址,打印它是没有意义的。 Remove this.去掉这个。

             if (read_size < 0)
             {
                 printf("%d\n",strerror(errno));
                 printf("Data not written to the file:\n");
                 gets(a);
                 goto free;
             }

Here you are missing a test for read_size == 0 , which indicates end of stream, whereupon you should close the socket and exit the loop.在这里,您缺少对read_size == 0的测试,它表示流结束,因此您应该关闭套接字并退出循环。

              printf("Buffer size value is  :%d \n",buffersize);

Third time you've printed this value, which hasn't changed, and fourth time you've printed this message, once with a bogus value.第三次打印这个值,它没有改变,第四次打印这个消息,一次是伪造的值。 Remove this.去掉这个。

This whole loop, including the bogus ioctl() and test, and the malloc() and free() , can be reduced to:整个循环,包括伪造的ioctl()和 test,以及malloc()free() ,可以简化为:

int read_size;
char buffer[8192];
while ((read_size = recv(socket, buffer, sizeof buffer, 0)) > 0)
{
    fwrite(pBuf, 1, read_size, text); // plus error handling ...
}
if (read_size < 0)
    // print the error as you are doing.

Your Java code is equally flaky.您的 Java 代码同样脆弱。 I won't comment in detail but it can all be reduced to this:我不会详细评论,但都可以简化为:

int bytesRead;
while ((bytesRead = is.read(mybytearray)) > 0)
{
    fos.write(mybytearray, 0, bytesRead);
}

Until all this is fixed, at both ends, this will never work.在这一切都解决之前,在两端,这永远不会奏效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM