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

标签 java c sockets unix tcp

我必须向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;
 }

最佳答案

这是质量非常差的代码。

发送循环:

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。 *可在不阻塞的情况下读取的字节数buffersize给出,*当且仅当*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 不是“缓冲区大小值”,它是缓冲区的地址,打印它是没有意义的。删除这个。

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

在两端的所有问题都得到解决之前,这永远不会起作用。

关于java - 如何通过tcp/ip从java接收文件到C?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31739033/

相关文章:

java - 如何在没有过于复杂的代码的情况下为 Adapter 编写 JUnit?

java - 这个 "Image Fetcher 0"有什么作用?

java - java从服务器发送文件到客户端

c++ - 在单独的文件夹中编译对象,隐式规则不匹配

java - 限制 imageIO.write 套接字的传输速率

c# - 在 UDP 服务器中接收数据包时连接重置

java - 自定义类加载器时,两个groovy类相互导入导致循环编译错误

java - 如何在 Spring Boot 应用程序的 Feign 客户端上使用 WireMock?

我可以为了分析目的人为地减慢 C trig 函数吗?

为 ARM 进行 Clang 交叉编译?