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

时间:2015-07-31 05:58:22

标签: java c sockets unix tcp-ip

我必须将文件发送到java,java必须接收该文件并通过tcp / ip将其发送回C.我能够发送文件但在接收时我无法接收任何数据。我提供的代码供参考。

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;
}

添加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();
    }
  }

我正在提供我目前在程序中使用的接收代码

    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;
 }

我根据您的修改

放置代码
 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;
 }

1 个答案:

答案 0 :(得分:5)

这是非常差的质量代码。

发送循环:

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); 
  • “发送尺寸值”不是size,而是stat
  • 在出现错误时重复此循环是没有意义的。
  • 重复它,而所有数据都没有被发送也是毫无意义的,除非套接字阻塞并且没有中断,你没有测试。更正确的版本是:

    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); 
    

接收循环:

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

此时缓冲区大小为sizeof buffer。可以在不阻塞is given by buffersize , *if and only if*的情况下读取的*字节数ioctl()`返回零。

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

没有'插座的大小'这样的东西。删除。

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

为什么呢?你还要做什么?删除整个测试和ioctl(),然后阻止在recv()下面。

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

你已经打印过了。删除。

           pBuf = malloc(buffersize);

这是浪费时间和空间。使用固定大小的缓冲区并在循环开始之前分配它。删除它。

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

pBuf不是'buffersize value`,它是缓冲区的地址,打印它是没有意义的。删除它。

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

在这里,您缺少read_size == 0的测试,它表示流的结束,因此您应该关闭套接字并退出循环。

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

第三次打印此值(未更改),第四次打印此消息时,一次使用虚假值。删除它。

整个循环,包括虚假ioctl()和测试,以及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.

您的Java代码同样不稳定。我不会详细评论,但它可以全部归结为:

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

直到所有这一切都得到解决,在两端,这将永远不会奏效。