简体   繁体   English

为什么0xFEFF出现在recv数据中

[英]Why 0xFEFF appear in recv data

i try to create a client written in c++ and a server using python flask.我尝试创建一个用 c++ 编写的客户端和一个使用 python flask 的服务器。 The task is simple, client connect and get data from server, then display it on console.任务很简单,客户端连接并从服务器获取数据,然后在控制台上显示。 I have two piece of code:我有两段代码:

Server:服务器:

from flask import Flask

app = Flask(__name__)

@app.route('/hello')
def hello():
    return "hello".encode("utf-16")


if __name__ == "__main__":
    app.run(debug=True,host="127.0.0.1")

Client:客户:

BOOL bResults = FALSE;
    bool ret = false;
    DWORD dwDownloaded = 0;
    WCHAR wDataRecv[1024] = {0};
    HINTERNET hConnect = NULL;
    HINTERNET hRequest = NULL;
    DWORD dwSize = 0;

    HINTERNET hSession = WinHttpOpen(L"WinHTTP Example/1.0",
        WINHTTP_ACCESS_TYPE_DEFAULT_PROXY,
        WINHTTP_NO_PROXY_NAME,
        WINHTTP_NO_PROXY_BYPASS, 0); # open session to connect
    hConnect = WinHttpConnect(hSession, L"localhost", (port == 0) ? INTERNET_DEFAULT_HTTP_PORT : port, 0); # connect to localhost with port 80 or custom port (this time i use port 5000)
    if (!hConnect)
        goto Free_And_Exit;
    hRequest = WinHttpOpenRequest(hConnect, L"GET", L"/hello", NULL, WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, 0); 
    
    if (hRequest) {
        bResults = WinHttpSendRequest(hRequest, NULL, 0,WINHTTP_NO_REQUEST_DATA, 0,0, 0);# send GET request
    }

    if (bResults)
        bResults = WinHttpReceiveResponse(hRequest, NULL);

    if (bResults)
    {
        dwSize = 0;
        if (!WinHttpQueryDataAvailable(hRequest, &dwSize)) {
            std::cout << "WinHttpQueryDataAvailable failed with code: " << GetLastError();
        }
        if (!WinHttpReadData(hRequest, wDataRecv, dwSize, &dwDownloaded)) {
            std::cout << "WinHttpReadData failed with code: " << GetLastError();
        }
        std::wcout << wDataRecv; # wcout wont print anything to console
    }
Free_And_Exit: #clean up
    if (hRequest) WinHttpCloseHandle(hRequest);
    if (hConnect) WinHttpCloseHandle(hConnect);
    return ret;

I noticed that the data return from server like:我注意到从服务器返回的数据如下:

b'\xfe\xff\hello' b'\xfe\xff\你好'

Why 0xFEFF is there?为什么有 0xFEFF?

Its is BOM (byte order mark).它是BOM(字节顺序标记)。 I just need to decode from the client or use:我只需要从客户端解码或使用:

return "hello".encode('UTF-16LE') # not UTF-16

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM