java - java客户端和c服务器之间的文件传输

标签 java c sockets client-server file-transfer

我正在尝试从 java 客户端发送文件到 c 服务器......问题是我的 c 服务器一次只接收 1 个字节,无论缓冲区大小如何......我想传输一次以 block 为单位的数据(可能是 512 字节或更多)......有人可以看一下并指出哪里出了问题或必须更改......提前致谢......

C 服务器:

    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
    #include <sys/ioctl.h>
    #include <sys/types.h>
    #include <sys/socket.h>
    #include <netinet/in.h>
    #include <pthread.h>

    #define PORT 8880
    #define filename "incoming.txt"

    void* thread_proc(void *arg);

    int main(int argc, char *argv[])
    {
        struct sockaddr_in sAddr;
        int sockfd,connfd;
        int status;
        pthread_t thread_id;
        int val;

        sockfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);

        val = 1;
        status = setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &val, sizeof(val));
        if (status < 0) {
            perror("Error - port");
            return 0;
        }

        sAddr.sin_family = AF_INET;
        sAddr.sin_port = htons(PORT);
        sAddr.sin_addr.s_addr = INADDR_ANY;

        status = bind(sockfd, (struct sockaddr *) &sAddr, sizeof(sAddr));
        if (status < 0) {
            perror("Error - Bind");
            return 0;
        }

        status = listen(sockfd, 5);
        if (status < 0) {
            perror("Error - Listen");
            return 0;
        }

       while(1) {
           connfd = accept(sockfd, NULL, NULL);
           if (connfd < 0) { 
               printf("Accept error on server\n");
               error("ERROR on accept"); 
               return 0;
           }
           printf("client connected to child thread %i with pid %i.\n", pthread_self(), getpid());
           status = pthread_create(&thread_id, NULL, thread_proc, (void *) connfd);
           if (status != 0) {
               printf("Could not create thread.\n");
               return 0;
           }
           sched_yield();
        }
        pthread_join (thread_id, NULL);
    }

    void* thread_proc(void *arg)
    {
        int connfd;
        int nread,n;
        char buffer[1024];
        FILE *fp;

        connfd = (int) arg;

        fp = fopen(filename, "ab");

        if (fp == NULL) 
        {
            printf("File not found!\n");
            return NULL;
        }
        else 
        {
            printf("Found file %s\n", filename);
        } 
        while (n = recv(connfd, buffer, sizeof buffer, 0) > 0) {
                fwrite(buffer, sizeof(char), n, fp);
                fprintf(stdout, "Received %d bytess\n", n);
        }
        fclose(fp);
        close(connfd);
        printf("client disconnected from child thread %i with pid %i.\n", pthread_self(), getpid());
        return NULL;
    }

Java 客户端:

    import java.net.*;
    import java.io.*;
    import java.util.Arrays;

    // A client for our multithreaded EchoServer.
    public class client
    {
        public static void main(String[] args)
        {
            Socket socket = null;
            int PORT = 8880;

           // Create the socket connection to the EchoServer.
            try
            {
                socket = new Socket("localhost", PORT);
            }        
            catch(UnknownHostException uhe)
            {
                // Host unreachable
                System.out.println("Unknown Host");
                socket = null;
            }
            catch(IOException ioe)
            {
                // Cannot connect to port on given host
                System.out.println("Cant connect to server at 8880. Make sure it is running.");
                socket = null;
            }

            if(socket == null)
                System.exit(-1);
            try
            {
                File file = new File("ext.txt");
                byte[] bytes = new byte[8192];
                FileInputStream fis = new FileInputStream(file);
                BufferedInputStream bis = new BufferedInputStream(fis);
                OutputStream out = socket.getOutputStream();

                int count,file_size;

                while ((count = bis.read(bytes)) > 0) {
                    System.out.println(count);
                    out.write(bytes, 0, count);
                }
                out.flush();
                out.close();
                fis.close();
                bis.close();
            }  
            catch(IOException ioe)
            {
                System.out.println("Exception during communication. Server probably closed connection.");
            }
            finally
            {
                try
                {
                    // Close the socket before quitting
                    socket.close();
                }
                catch(Exception e)
                {
                    e.printStackTrace();
                }                
            }        
        }
    }

最佳答案

检查这些代码

服务器

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <pthread.h>
#include <error.h>

#define PORT 5000
#define filename "incoming.txt"

void* thread_proc(void *arg);

int main(int argc, char *argv[])
{
    struct sockaddr_in sAddr;
    int sockfd,connfd;
    int status;
    pthread_t thread_id;
    int val;

    sockfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);

    val = 1;
    status = setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &val, sizeof(val));
    if (status < 0) {
        perror("Error - port");
        return 0;
    }

    sAddr.sin_family = AF_INET;
    sAddr.sin_port = htons(PORT);
    sAddr.sin_addr.s_addr = INADDR_ANY;

    status = bind(sockfd, (struct sockaddr *) &sAddr, sizeof(sAddr));
    if (status < 0) {
        perror("Error - Bind");
        return 0;
    }

    status = listen(sockfd, 5);
    if (status < 0) {
        perror("Error - Listen");
        return 0;
    }

   while(1) {
       connfd = accept(sockfd, NULL, NULL);
       if (connfd < 0) { 
           printf("Accept error on server\n");
           //error("ERROR on accept"); 
           return 0;
       }
       printf("client connected to child thread %i with pid %i.\n", pthread_self(), getpid());
       status = pthread_create(&thread_id, NULL, thread_proc, (void *) connfd);
       if (status != 0) {
           printf("Could not create thread.\n");
           return 0;
       }
       sched_yield();
    }
    pthread_join (thread_id, NULL);
}

void* thread_proc(void *arg)
{
    int connfd;
    int nread,n;
    char buffer[1000];
    FILE *fp;

    connfd = (int) arg;

    fp = fopen(filename, "ab");

    if (fp == NULL) 
    {
        printf("File not found!\n");
        return NULL;
    }
    else 
    {
        printf("Found file %s\n", filename);
    } 
    while ((n = recv(connfd, buffer, sizeof buffer, 0)) > 0) {
            fwrite(buffer, sizeof(char), n, fp);
            fprintf(stdout, "Received %d bytess\n", n);
    }
    fclose(fp);
    close(connfd);
    printf("client disconnected from child thread %i with pid %i.\n", pthread_self(), getpid());
    return NULL;
}

客户端

 import java.net.*;
    import java.io.*;
    import java.util.Arrays;

    // A client for our multithreaded EchoServer.
    public class client
    {
        public static void main(String[] args)
        {
            Socket socket = null;
            int PORT = 5000;

           // Create the socket connection to the EchoServer.
            try
            {
                socket = new Socket("localhost", PORT);
            }        
            catch(UnknownHostException uhe)
            {
                // Host unreachable
                System.out.println("Unknown Host");
                socket = null;
            }
            catch(IOException ioe)
            {
                // Cannot connect to port on given host
                System.out.println("Cant connect to server at 5000. Make sure it is running.");
                socket = null;
            }

            if(socket == null)
                System.exit(-1);
            try
            {
                File file = new File("ext.txt");
                byte[] bytes = new byte[8192];
                FileInputStream fis = new FileInputStream(file);
                BufferedInputStream bis = new BufferedInputStream(fis);
                OutputStream out = socket.getOutputStream();

                int count,file_size;

                while ((count = bis.read(bytes)) > 0) {
                    System.out.println(count);
                    out.write(bytes, 0, count);
                }
                out.flush();
                out.close();
                fis.close();
                bis.close();
            }  
            catch(IOException ioe)
            {
                System.out.println("Exception during communication. Server probably closed connection.");
            }
            finally
            {
                try
                {
                    // Close the socket before quitting
                    socket.close();
                }
                catch(Exception e)
                {
                    e.printStackTrace();
                }                
            }        
        }
    }

我刚刚使用端口 5000 并使用 nc 命令来检查您的服务器..它工作正常

我认为您需要做的是更改您的端口。我检查了运行它们:)

-快乐编码-

关于java - java客户端和c服务器之间的文件传输,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27498845/

相关文章:

java - 在 jtext 区域中打印 unicode 字词时出现 ArrayIndexOutofBoundException。 (马拉雅拉姆语词)

c中的聊天客户端

python - 如何在 Linux 中模拟套接字连接超时?

java - 将字节数组转换为 JSONArray 的简单方法

java - 根据 JComboBox 选择添加 JList 项目

c - 无法计算输出中的行数

c - 如何访问结构数组中的结构

c - 是否可以将 `splice()` 从套接字传输到 "zero-copy"缓冲区?

javascript - 客户端无法获取握手错误消息

java - 如何确定用户显示的中点?