简体   繁体   English

如何从 python 服务器正确发送消息到 c++ 客户端?

[英]How to send messages properly from python server to c++ client?

I have a python server running on the following code:我有一个 python 服务器在以下代码上运行:

import socket
ss=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
ss.bind(('0.0.0.0',8080))
ss.listen(5)
cs,adr=ss.accept()
print("Got a connection from:"+str(adr))
while 1:
    msg=input('Enter your message:')
    cs.send(msg.encode('ascii'))
cs.close()

For client I'm using C++.对于客户端,我使用的是 C++。
client.h:客户端.h:

#include<WinSock2.h>
#include<WS2tcpip.h>
#include<iostream>
#pragma comment(lib,"ws2_32.lib")
#pragma warning(disable:4996)
class client {
private:
    const char* IP;
    int PORT;
    SOCKET sock;
public:
    client(char* ip, int port){
        IP = ip;
        PORT = port;
    }
    void createSession();//Creates socket and connects with the server.
    void sendData(char* message);//Sends message to the server, it works fine
    char* receive()
    {
        char message[2000];
        if (recv(sock, message, 2000, 0) == SOCKET_ERROR)
        {
            WSACleanup();
            return (char*)"Failed to receive Message";
        }
        return message;
    }
};

client.cpp:客户端.cpp:

#include"client.h"
#include<iostream>
#define IP "127.0.0.1"
#define port 8080
using namespace std;
int main()
{
    client c1((char*)IP, port);
    c1.createSession();
    while (1)
    {
        char* message;
        message = c1.receive();
        cout << IP << ':' << port << " Says: " << message << endl;
    }
    return 0;
}

but the message that I'm receiving is garbage.但我收到的信息是垃圾。 I'm guessing it's a conversion error because for python clients, I'd use recv(length).decode('ascii') to decode the message first when receiving.我猜这是一个转换错误,因为对于 python 客户端,我会在接收时首先使用recv(length).decode('ascii')来解码消息。 How do I fix this?我该如何解决?

char* receive()
{
    char message[2000];
    if (recv(sock, message, 2000, 0) == SOCKET_ERROR)
    {
        WSACleanup();
        return (char*)"Failed to receive Message";
    }
    return message;
}
...
message = c1.receive();
cout << IP << ':' << port << " Says: " << message << endl;

This is wrong in multiple places:这在多个地方都是错误的:

  • You are reading the data into a buffer allocated on the function stack ( message[2000] ).您正在将数据读入分配在 function 堆栈( message[2000] )上的缓冲区中。 This buffer will be automatically freed after the functions exits, so what you return from the function is no longer there.该缓冲区将在函数退出后自动释放,因此您从 function 返回的内容不再存在。
  • When printing you treat the message as a \0 -terminated char[] even though its not \0 terminated.打印时,您将消息视为\0终止的 char[] ,即使它不是\0终止的。 This means that garbage after the received message will be printed though, until a \0 gets found.这意味着接收消息之后的垃圾将被打印,直到找到\0为止。 It might well be that no \0 gets found within the buffer in which case it will continue to read, possibly outside allocated memory and thus crash.很可能在缓冲区中找不到\0 ,在这种情况下它将继续读取,可能在分配的 memory 之外并因此崩溃。
  • You assume that the send in Python will send the full message but this is not guaranteed.您假设 Python 中的send将发送完整消息,但这不能保证。 Check the return value of send on how much was actually send or use sendall .检查send的返回值,了解实际发送了多少或使用sendall
  • You assume that recv in C will receive the full message but this is not guaranteed.您假设 C 中的recv将收到完整的消息,但这不能保证。 TCP has no concept of a message and recv will return just return the bytes already received. TCP 没有消息的概念, recv只会返回已经收到的字节。 Especially with large messages or small TCP windows this might not be the complete message you intended.特别是对于大消息或小消息 TCP windows 这可能不是您想要的完整消息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 将 QImage 从 c++ 客户端发送到 python 服务器 - Send QImage from c++ client to python server Zeromq:如何从python客户端向C ++服务器发送长度超过30个字符的消息 - Zeromq : How to send message longer than 30 character from python client to c++ server 初始握手后,如何在 Python WebSockets 服务器中将消息从服务器发送到客户端? - How to send messages from server to client in a Python WebSockets server, AFTER initial handshake? 如何从Flask服务器(Python)向HTML客户端发送消息? - How do you send messages from Flask server (Python) to HTML client? 使用C ++ Client通过Zmq发送JSON对象-Python服务器 - Send JSON Object through Zmq with C++ Client - Python Server 如何在python中将消息从客户端发送到服务器 - How to send a message from client to server in python 如何在 python 中将图片从服务器发送到客户端 - how to send a picture from server to client in python 从扭曲的客户端向服务器发送多条消息 - Send multiple messages to server from twisted client 使用 sockets 将字符串从一台计算机上的 C++ 客户端发送到另一台计算机上的 Python 服务器。 获取`发送:错误的文件描述符` - Using sockets to send a string from a C++ client on one computer to a Python server on another. Getting `send: Bad file descriptor` 客户端服务器python -C ++ - client server python -C++
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM