有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java CServersocket变为错误数据包

我有以下问题:

  • 我有一个Java客户端,使用ApacheMina框架发送字符串
  • 我编写了一个C服务器来接收字符串
  • 因此,我尝试向服务器发送一个utf8字符:myStringToSend=“Ä”
  • 我调试了mina源代码以查看字节或十六进制格式的数据包,mina很好地转换了字符串,因此它发送了0xC3{}
  • 我还在wireshark网络查看器中检查发送的数据包,它也将0xC30x84视为数据包,一切正常
  • 但是我的C服务器接收以下字节:FFFFFFC3FFFFFF84

我不知道怎么了

我的C服务器的代码:

#include "stdafx.h"
#include <io.h>
#include <stdio.h>
#include <winsock2.h>

#pragma comment(lib,"ws2_32.lib") //Winsock Library

#define DEFAULT_BUFLEN 512
#define TOOBIG 100000

int main(int argc, char *argv[])
{
WSADATA wsa;
int i, c, iResult, iSendResult, outputCounter;

SOCKET listenSocket = INVALID_SOCKET, clientSocket = INVALID_SOCKET;
struct sockaddr_in server, client; 
char *message;

char sendbuf[DEFAULT_BUFLEN];
unsigned char recvbuf[DEFAULT_BUFLEN];
int recvbuflen = DEFAULT_BUFLEN;

printf("\nInitialising Winsock...");
if (WSAStartup(MAKEWORD(2,2),&wsa) != NO_ERROR)
{
    printf("Failed. Error Code : %d",WSAGetLastError());
    return 1;
}
printf("Initialised.\n");     

if((listenSocket = socket(AF_INET , SOCK_STREAM , IPPROTO_TCP )) == INVALID_SOCKET) //IPv4, TCP
{
    printf("Could not create socket : %d" , WSAGetLastError());
    WSACleanup();
    return 1;
}

printf("Socket created.\n");

memset(&server, '0', sizeof(server));
memset(sendbuf, '0', sizeof(sendbuf)); 

server.sin_family = AF_INET;
//server.sin_addr.s_addr = htonl(0x7F000001); //localhost - 127.0.0.1
server.sin_addr.s_addr = inet_addr("127.0.0.1");
//server.sin_addr.s_addr = inet_addr("10.48.53.166");
server.sin_port = htons(7368); 

if( bind(listenSocket ,(struct sockaddr *)&server , sizeof(server)) == SOCKET_ERROR)
{
    printf("Bind failed with error code : %d" , WSAGetLastError());
    closesocket(listenSocket);
    WSACleanup();
    return 1;
}

puts("Bind done");

listen(listenSocket, 10); 

//Accept and incoming connection
puts("Waiting for incoming connections...");


c = sizeof(struct sockaddr_in);

message = "{\"id\":2,\"result\":{\"code\":\"999\",\"message\":\"AddPageRange StartIndex don't match Inspection Counter\"},\"Client_ID\":\"PQCS1\",\"jsonrpc\":\"2.0\",\"Protocol\":\"2H\"}";

while( (clientSocket = accept(listenSocket , (struct sockaddr *)NULL, NULL)) != INVALID_SOCKET )
{
    puts("Connection accepted");        
    do {
        iResult = recv(clientSocket, recvbuf, recvbuflen, 0);
        if ( iResult > 0 )
        {
            printf("Bytes received: %d\n", iResult);
            recvbuf[iResult] = '\0';
            outputCounter = 0;
            while(recvbuf[outputCounter] != '\0')
                printf("%X", (unsigned char)recvbuf[outputCounter++]);              
            iSendResult = send( clientSocket, message, strlen(message), 0 );
            if (iSendResult == SOCKET_ERROR)
            {
                printf("send failed with error: %d\n", WSAGetLastError());
                closesocket(clientSocket);
                WSACleanup();
                return 1;
            }
            printf("Bytes sent: %d\n", iSendResult);
        }
        else if ( iResult == 0 )
            printf("Connection closed\n");
        else
            printf("recv failed: %d\n", WSAGetLastError());
    } while( iResult > 0 );

 }
if (clientSocket == INVALID_SOCKET)
{
    printf("accept failed with error code : %d" , WSAGetLastError());
    return 1;
}
closesocket(listenSocket);
WSACleanup();

return 0;
}

共 (2) 个答案

  1. # 1 楼答案

    你的recvbuf是char类型,怀疑你的平台上有签名。消息的两个字节都是>;127(十进制)等被视为负数。printf(“%X”)格式说明符需要一个整数(在您的平台上,从外观上看是32位),因此数字会得到符号扩展(用字节的最高有效位填充整数的最高有效24位)

    试着打印出你收到的字节数。同时将printf更改为

    printf("%X",  ((int)recvbuf[outputCounter++]) & 0xff);             
    
  2. # 2 楼答案

    你对printf有问题

    看着The Man

    o, u, x, X

    The unsigned int argument is converted to unsigned octal (o), unsigned decimal (u), or unsigned hexadecimal (x and X) notation. The letters abcdef are used for x conversions; the letters ABCDEF are used for X conversions. The precision, if any, gives the minimum number of digits that must appear; if the converted value requires fewer digits, it is padded on the left with zeros. The default precision is 1. When 0 is printed with an explicit precision 0, the output is empty.

    强调我的

    因此,使用%X作为格式说明符,您的数据将被提升为unsigned int,并且您必须通过它,只选择要打印的字节:

    printf("Byte %d: %X\n", outputCounter, recvbuf[outputCounter++] & 0xFF);