Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/design-patterns/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python3套接字客户端发送数据和C++;套接字服务器接收带有偏移量的数据? 我做了一个小测试,将一个Python应用程序(客户端套接字)的一个整数发送到一个C++应用程序(Socket Server),这两个都是TCP流套接字。我还测试了将相同的整数从python中的客户端套接字发送到python中的服务器套接字_Python_Sockets_Visual C++_Offset_Python 3.3 - Fatal编程技术网

Python3套接字客户端发送数据和C++;套接字服务器接收带有偏移量的数据? 我做了一个小测试,将一个Python应用程序(客户端套接字)的一个整数发送到一个C++应用程序(Socket Server),这两个都是TCP流套接字。我还测试了将相同的整数从python中的客户端套接字发送到python中的服务器套接字

Python3套接字客户端发送数据和C++;套接字服务器接收带有偏移量的数据? 我做了一个小测试,将一个Python应用程序(客户端套接字)的一个整数发送到一个C++应用程序(Socket Server),这两个都是TCP流套接字。我还测试了将相同的整数从python中的客户端套接字发送到python中的服务器套接字,python,sockets,visual-c++,offset,python-3.3,Python,Sockets,Visual C++,Offset,Python 3.3,我要做的是发送一个4字节的数组(c++中的字符),每个字符的整数右移(>>),如下所示(python语法): 问题是,当从python中的客户端套接字发送到python中的服务器套接字时,数据“到达ok”,例如,如果我发送整数1390248303 python服务器套接字首先打印接收到的字节流,然后为每个字节打印其ascii代码,然后执行以下操作: sum([l[3-i] << 8*i for i in (3,2,1,0)]) 但是C++服务器套接字,在代码中我做的代码相同,但代码

我要做的是发送一个4字节的数组(c++中的字符),每个字符的整数右移(>>),如下所示(python语法):

问题是,当从python中的客户端套接字发送到python中的服务器套接字时,数据“到达ok”,例如,如果我发送整数1390248303

python服务器套接字首先打印接收到的字节流,然后为每个字节打印其ascii代码,然后执行以下操作:

sum([l[3-i] << 8*i for i in (3,2,1,0)])

但是C++服务器套接字,在代码中我做的代码相同,但代码冗长:

...
int sum = 0;
int term = 0;
for(int i = 3;i > -1;i--)
{
    printf("%d\n",msg[3-i]);
    term = msg[3-i];
    //if (term < 0)
    //  term = 256 + term;
    suma += term << 8*i;                
};
printf("Received: %d\n",sum);
...

你是否看到中间的2个字节与中间的2个字节不同,对应于Python中的服务器套接字输出什么?不仅如此,如果我加上256个,它们就变得一样了:

 -35 + 256 = 221
-127 + 256 = 129
这种行为的原因是什么?事先谢谢你的任何提示

以下是应用程序的代码:

python客户端套接字:

import socket
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect(("localhost", 7000))
my_int = 1390248303
my_bytes = bytearray()        
for e in [my_int >> i & 0xff for i in (24,16,8,0)]:
    my_bytes.append(e)
print("To be sent:", my_bytes)    
client_socket.send(my_bytes)
print("Sent:", my_bytes)    
client_socket.close()
python服务器套接字:

import socket
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind(("", 7000))
server_socket.listen(5)

print("TCPServer Waiting for client on port 7000")

while 1:
    client_socket, address = server_socket.accept()
    print("I got a connection from ", address)
    while 1:
        data = client_socket.recv(32)
        print("RECEIVED:",data)
        l = []
        for e in data:
            l.append(e)
            print(e)
        print("RECEIVED:",sum([l[3-i] << 8*i for i in (3,2,1,0)]))
        if (data == b''):
            break;
    break;
#define WIN32_LEAN_AND_MEAN

#include <WinSock2.h>
#include <WS2tcpip.h>
#include <stdio.h>
#include <stdlib.h>


// link with Ws2_32.lib
#pragma comment(lib, "Ws2_32.lib")

#define DEFAULT_PORT "7000"
//"27015"
#define DEFAULT_BUFFER_LENGTH 32
//512

int main() {

    WSADATA wsaData;

    // Initialize Winsock
    int iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
    if(iResult != 0)
    {
        printf("WSAStartup failed: %d\n", iResult);
        return 1;
    }

    struct addrinfo *result = NULL,
                    hints;

    ZeroMemory(&hints, sizeof(hints));
    hints.ai_family = AF_INET;      // Internet address family is unspecified so that either an IPv6 or IPv4 address can be returned
    hints.ai_socktype = SOCK_STREAM;    // Requests the socket type to be a stream socket for the TCP protocol
    hints.ai_protocol = IPPROTO_TCP;
    hints.ai_flags = AI_PASSIVE;

    // Resolve the local address and port to be used by the server
    iResult = getaddrinfo(NULL, DEFAULT_PORT, &hints, &result);
    if (iResult != 0)
    {
        printf("getaddrinfo failed: %d\n", iResult);
        WSACleanup();
        return 1;
    }

    SOCKET ListenSocket = INVALID_SOCKET;

    // Create a SOCKET for the server to listen for client connections
    ListenSocket = socket(result->ai_family, result->ai_socktype, result->ai_protocol);

    if (ListenSocket == INVALID_SOCKET)
    {
        printf("Error at socket(): %d\n", WSAGetLastError());
        freeaddrinfo(result);
        WSACleanup();
        return 1;
    }

    // Setup the TCP listening socket
    iResult = bind(ListenSocket, result->ai_addr, (int)result->ai_addrlen);

    if (iResult == SOCKET_ERROR)
    {
        printf("bind failed: %d", WSAGetLastError());
        freeaddrinfo(result);
        closesocket(ListenSocket);
        WSACleanup();
        return 1;
    }

    freeaddrinfo(result);

    // To listen on a socket
    if ( listen(ListenSocket, SOMAXCONN) == SOCKET_ERROR)
    {
        printf("listen failed: %d\n", WSAGetLastError());
        closesocket(ListenSocket);
        WSACleanup();
        return 1;
    }

    SOCKET ClientSocket;

    ClientSocket = INVALID_SOCKET;

    // Accept a client socket
    ClientSocket = accept(ListenSocket, NULL, NULL);

    if (ClientSocket == INVALID_SOCKET)
    {
        printf("accept failed: %d\n", WSAGetLastError());
        closesocket(ListenSocket);
        WSACleanup();
        return 1;
    }

    char recvbuf[DEFAULT_BUFFER_LENGTH];
    int iSendResult;

    // receive until the client shutdown the connection
    do {
        iResult = recv(ClientSocket, recvbuf, DEFAULT_BUFFER_LENGTH, 0);
        if (iResult > 0)
        {
            char msg[DEFAULT_BUFFER_LENGTH];
            memset(&msg, 0, sizeof(msg));
            strncpy(msg, recvbuf, iResult);         

            printf("Received: %s\n", msg);
                    //Here is where I implement the python code:
            //sum([l[3-i] << 8*i for i in (3,2,1,0)]));
            int sum = 0;
            int term = 0;
            for(int i = 3;i > -1;i--)
            {
                printf("%d\n",msg[3-i]);
                term = msg[3-i];
                //if (term < 0)
                //  term = 256 + term;
                sum += term << 8*i;             
            };
            printf("Received: %d\n",sum);

            iSendResult = send(ClientSocket, recvbuf, iResult, 0);

            if (iSendResult == SOCKET_ERROR)
            {
                printf("send failed: %d\n", WSAGetLastError());
                closesocket(ClientSocket);
                WSACleanup();

                getchar();
                return 1;
            }

            printf("Bytes sent: %ld\n", iSendResult);
        }
        else if (iResult == 0)
            printf("Connection closed\n");
        else
        {
            printf("recv failed: %d\n", WSAGetLastError());
            closesocket(ClientSocket);
            WSACleanup();

            getchar();
            return 1;
        }
    } while (iResult > 0);

    // Free the resouces
    closesocket(ListenSocket);
    WSACleanup();

    getchar();
    //while (true){};
    return 0;
}
导入套接字
server\u socket=socket.socket(socket.AF\u INET,socket.SOCK\u流)
服务器\u套接字.bind(“”,7000))
服务器\u套接字。侦听(5)
打印(“TCPServer在端口7000上等待客户端”)
而1:
客户端\u套接字,地址=服务器\u套接字.accept()
打印(“我从”,地址获得连接)
而1:
data=client_socket.recv(32)
打印(“接收:”,数据)
l=[]
对于数据中的e:
l、 附加(e)
打印(e)
打印(“接收:”,和([l[3-i]ai_系列,结果->ai_类型,结果->ai_协议);
if(ListenSocket==无效的_套接字)
{
printf(“套接字()处的错误:%d\n”,WSAGetLastError());
freeaddrinfo(结果);
WSACleanup();
返回1;
}
//设置TCP侦听套接字
iResult=bind(ListenSocket,result->ai_addr,(int)result->ai_addrlen);
if(iResult==SOCKET\u错误)
{
printf(“绑定失败:%d”,WSAGetLastError());
freeaddrinfo(结果);
闭合插座(ListenSocket);
WSACleanup();
返回1;
}
freeaddrinfo(结果);
//监听插座
if(侦听(ListenSocket,SOMAXCONN)=套接字错误)
{
printf(“侦听失败:%d\n”,WSAGetLastError());
闭合插座(ListenSocket);
WSACleanup();
返回1;
}
插座客户端插座;
ClientSocket=无效的_套接字;
//接受客户端套接字
ClientSocket=accept(ListenSocket,NULL,NULL);
if(ClientSocket==无效的_SOCKET)
{
printf(“接受失败:%d\n”,WSAGetLastError());
闭合插座(ListenSocket);
WSACleanup();
返回1;
}
char recvbuf[默认缓冲区长度];
int iSendResult;
//接收,直到客户端关闭连接
做{
iResult=recv(ClientSocket,recvbuf,默认缓冲区长度,0);
如果(iResult>0)
{
char msg[默认缓冲区长度];
memset(&msg,0,sizeof(msg));
strncpy(msg、recvbuf、iResult);
printf(“收到:%s\n”,msg);
//下面是我实现python代码的地方:
//总和([l[3-i]-1;i--)
{
printf(“%d\n”,msg[3-i]);
术语=味精[3-i];
//如果(项<0)
//期限=256+期限;
总和+=第0项);
//释放资源
闭合插座(ListenSocket);
WSACleanup();
getchar();
//而(对){};
返回0;
}

msg[]
被声明为
char
,但不保证是。请使用
无符号char

两条线

            printf("%d\n",msg[3-i]);
            term = msg[3-i];

<> >将符号转换为符号整数。<代码> %d < /代码>使用<代码> %u < /代码>。<代码>术语<代码>被声明为“代码> int <代码>,使其成为代码>未签名的int < < /P> < P> > @ ANTE建议,我在C++服务器套接字中更改了代码,也将ReVBUF更改为无符号char,并将int从int到无符号int求和以实现一致性。(毕竟,我在等待接收未签名字符并“重建”未签名int),但它也能让recvbuf和sum保持原样

问题是,为了表示这么大的整数,我实际上使用了一个无符号整数,发送的字节是ascii码,其范围为0-255(与无符号字符的范围相同),字符范围为-127-126

尽管如此,套接字并不关心数据类型,它们只发送二进制数据,所以我接收到的是无符号字符,当放入字符时,它们会“溢出”并变为负数(从技术上讲,这是因为我认为是如何工作的)

关于更正后的代码,还有一些注意事项:

1) 这个

if(术语<0)
期限=256+期限;
不再需要(实际上我正在手动修复溢出问题)

2) 我必须使用cast to char*(char)才能使用recv、strncpy和send,它们将char作为参数,而不是unsigned char*。这项工作很有效,我认为这不是黑客行为,因为指向char的指针和指向unsigned char的指针都指向内存中大小相同(8位)的数据类型。如果这是错误的,或可能导致不必要或意外的行为,请纠正我

    //char recvbuf[DEFAULT_BUFFER_LENGTH];
    unsigned char recvbuf[DEFAULT_BUFFER_LENGTH];
    int iSendResult;

    // receive until the client shutdown the connection
    do {
        //iResult = recv(ClientSocket, recvbuf, DEFAULT_BUFFER_LENGTH, 0);
        iResult = recv(ClientSocket, (char *)recvbuf, DEFAULT_BUFFER_LENGTH, 0);
        if (iResult > 0)
        {
            //char msg[DEFAULT_BUFFER_LENGTH];
            unsigned char msg[DEFAULT_BUFFER_LENGTH];
            memset(&msg, 0, sizeof(msg));
            //strncpy((msg, recvbuf, iResult);  
            strncpy((char *)msg, (char *)recvbuf, iResult);         

            printf("Received: %s\n", msg);

            //sum([l[3-i] << 8*i for i in (3,2,1,0)]));
            //int sum = 0;
            unsigned int sum = 0;
            //int term = 0;
            unsigned int term = 0;
            for(int i = 3;i > -1;i--)
            {
                //printf("%d\n",msg[3-i]);
                printf("%u\n",msg[3-i]);
                term = msg[3-i];                    
                sum += term << 8*i;             
            };
            //printf("Received: %d\n",sum);
            printf("Received: %u\n",sum);

            //iSendResult = send(ClientSocket, recvbuf, iResult, 0);
            iSendResult = send(ClientSocket, (char *) recvbuf, iResult, 0);
//char recvbuf[默认缓冲区长度];
无符号字符recvbuf[默认缓冲区长度];
int iSendResult;
//接收,直到客户端关闭连接
做{
//iResult=recv(ClientSocket,recvbuf,默认缓冲区长度,0);
iResult=recv(ClientSocket,(char*)recvbuf,默认缓冲区长度,0);
如果(iResult>0)
{
//char msg[默认缓冲区长度];
无符号字符消息[默认缓冲区长度];
#define WIN32_LEAN_AND_MEAN

#include <WinSock2.h>
#include <WS2tcpip.h>
#include <stdio.h>
#include <stdlib.h>


// link with Ws2_32.lib
#pragma comment(lib, "Ws2_32.lib")

#define DEFAULT_PORT "7000"
//"27015"
#define DEFAULT_BUFFER_LENGTH 32
//512

int main() {

    WSADATA wsaData;

    // Initialize Winsock
    int iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
    if(iResult != 0)
    {
        printf("WSAStartup failed: %d\n", iResult);
        return 1;
    }

    struct addrinfo *result = NULL,
                    hints;

    ZeroMemory(&hints, sizeof(hints));
    hints.ai_family = AF_INET;      // Internet address family is unspecified so that either an IPv6 or IPv4 address can be returned
    hints.ai_socktype = SOCK_STREAM;    // Requests the socket type to be a stream socket for the TCP protocol
    hints.ai_protocol = IPPROTO_TCP;
    hints.ai_flags = AI_PASSIVE;

    // Resolve the local address and port to be used by the server
    iResult = getaddrinfo(NULL, DEFAULT_PORT, &hints, &result);
    if (iResult != 0)
    {
        printf("getaddrinfo failed: %d\n", iResult);
        WSACleanup();
        return 1;
    }

    SOCKET ListenSocket = INVALID_SOCKET;

    // Create a SOCKET for the server to listen for client connections
    ListenSocket = socket(result->ai_family, result->ai_socktype, result->ai_protocol);

    if (ListenSocket == INVALID_SOCKET)
    {
        printf("Error at socket(): %d\n", WSAGetLastError());
        freeaddrinfo(result);
        WSACleanup();
        return 1;
    }

    // Setup the TCP listening socket
    iResult = bind(ListenSocket, result->ai_addr, (int)result->ai_addrlen);

    if (iResult == SOCKET_ERROR)
    {
        printf("bind failed: %d", WSAGetLastError());
        freeaddrinfo(result);
        closesocket(ListenSocket);
        WSACleanup();
        return 1;
    }

    freeaddrinfo(result);

    // To listen on a socket
    if ( listen(ListenSocket, SOMAXCONN) == SOCKET_ERROR)
    {
        printf("listen failed: %d\n", WSAGetLastError());
        closesocket(ListenSocket);
        WSACleanup();
        return 1;
    }

    SOCKET ClientSocket;

    ClientSocket = INVALID_SOCKET;

    // Accept a client socket
    ClientSocket = accept(ListenSocket, NULL, NULL);

    if (ClientSocket == INVALID_SOCKET)
    {
        printf("accept failed: %d\n", WSAGetLastError());
        closesocket(ListenSocket);
        WSACleanup();
        return 1;
    }

    char recvbuf[DEFAULT_BUFFER_LENGTH];
    int iSendResult;

    // receive until the client shutdown the connection
    do {
        iResult = recv(ClientSocket, recvbuf, DEFAULT_BUFFER_LENGTH, 0);
        if (iResult > 0)
        {
            char msg[DEFAULT_BUFFER_LENGTH];
            memset(&msg, 0, sizeof(msg));
            strncpy(msg, recvbuf, iResult);         

            printf("Received: %s\n", msg);
                    //Here is where I implement the python code:
            //sum([l[3-i] << 8*i for i in (3,2,1,0)]));
            int sum = 0;
            int term = 0;
            for(int i = 3;i > -1;i--)
            {
                printf("%d\n",msg[3-i]);
                term = msg[3-i];
                //if (term < 0)
                //  term = 256 + term;
                sum += term << 8*i;             
            };
            printf("Received: %d\n",sum);

            iSendResult = send(ClientSocket, recvbuf, iResult, 0);

            if (iSendResult == SOCKET_ERROR)
            {
                printf("send failed: %d\n", WSAGetLastError());
                closesocket(ClientSocket);
                WSACleanup();

                getchar();
                return 1;
            }

            printf("Bytes sent: %ld\n", iSendResult);
        }
        else if (iResult == 0)
            printf("Connection closed\n");
        else
        {
            printf("recv failed: %d\n", WSAGetLastError());
            closesocket(ClientSocket);
            WSACleanup();

            getchar();
            return 1;
        }
    } while (iResult > 0);

    // Free the resouces
    closesocket(ListenSocket);
    WSACleanup();

    getchar();
    //while (true){};
    return 0;
}
            printf("%d\n",msg[3-i]);
            term = msg[3-i];
if (term < 0)
    term = 256 + term;
    //char recvbuf[DEFAULT_BUFFER_LENGTH];
    unsigned char recvbuf[DEFAULT_BUFFER_LENGTH];
    int iSendResult;

    // receive until the client shutdown the connection
    do {
        //iResult = recv(ClientSocket, recvbuf, DEFAULT_BUFFER_LENGTH, 0);
        iResult = recv(ClientSocket, (char *)recvbuf, DEFAULT_BUFFER_LENGTH, 0);
        if (iResult > 0)
        {
            //char msg[DEFAULT_BUFFER_LENGTH];
            unsigned char msg[DEFAULT_BUFFER_LENGTH];
            memset(&msg, 0, sizeof(msg));
            //strncpy((msg, recvbuf, iResult);  
            strncpy((char *)msg, (char *)recvbuf, iResult);         

            printf("Received: %s\n", msg);

            //sum([l[3-i] << 8*i for i in (3,2,1,0)]));
            //int sum = 0;
            unsigned int sum = 0;
            //int term = 0;
            unsigned int term = 0;
            for(int i = 3;i > -1;i--)
            {
                //printf("%d\n",msg[3-i]);
                printf("%u\n",msg[3-i]);
                term = msg[3-i];                    
                sum += term << 8*i;             
            };
            //printf("Received: %d\n",sum);
            printf("Received: %u\n",sum);

            //iSendResult = send(ClientSocket, recvbuf, iResult, 0);
            iSendResult = send(ClientSocket, (char *) recvbuf, iResult, 0);