c服务器/java客户端之间的通信问题

时间:2021-02-06 13:55:34

标签: java c server tcp client

我需要通过 tcp 将消息从 java 客户端发送到 c 服务器。在java中我使用PrintWriter并发送三个字符串:操作是0和8之间的数字,消息的长度和消息。

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    out = new PrintWriter(new BufferedWriter(
                            new OutputStreamWriter(socket.getOutputStream())),true);
                    String op_code = String.valueOf(MainActivity.LOGIN);
                    String command = username + "#" + psw;
                    int len = command.length() + 1;
                    out.println(MainActivity.LOGIN);
                    out.println(len);
                    out.println(command);
                    Log.d("ciao", "run: ciao");
                    //String text = stdIn.readLine();
                    //int result = Integer.parseInt(text);
                    //sendDataToActivity("ACTION",result);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();

在 c 中,我只有 3 个 read()。第一个读取op_code

    char op_code [sizeof(uint8_t)];
    //printf("L'utente %s si è connesse\n",tc_info->username);

   /** @todo sostituire con variabili di condizione **/
    while(true){

        memset(op_code,'\0',sizeof(uint8_t));
        if(readn(sock,op_code,sizeof(uint8_t))<0)
             break;
        printf("opcode->%s\n",op_code);       
        if(atoi(op_code) == 0)
            break;
            
        select_op(sock,atoi(op_code), &tc_info);
    }  

Select_op 调用这部分代码处理另外两个read()

    int readbyte;
    char* command;
    readbyte = read_sign_inup_request(&command,fd); 
    if(readbyte<=0)
        {printf("error\n");return;}
int read_sign_inup_request(char** dest, int src){
   
    char len [sizeof(uint8_t)];
    int readed_byte;
    
    memset(len,'\0',sizeof(uint8_t));

    if((readed_byte=read(src,len,(sizeof(uint8_t)))==0))
        {printf("readed -> %d\n",readed_byte); return readed_byte;}
    printf("readed -> %d\n",readed_byte); 
    printf("len->%s\n",len);                      //**BROKEN HERE**

    int casted_length = atoi(len) ;
    *dest = (char*)malloc(casted_length);

    memset(*dest,'\0' ,casted_length);
    if((readed_byte=read(src,*dest,casted_length))==0)
        {return readed_byte;}
        
    return readed_byte;
}

我的问题是 len 始终为 0,我认为问题在于他的大小,但我不确定如何解决。有人可以帮我吗?

0 个答案:

没有答案