繁体   English   中英

unsigned char 到 char * 用于从 C++ WinSock 客户端到 C# 服务器的 TCP

[英]unsigned char to char * for TCP from C++ WinSock client to C# Server

我遇到了一个问题,我认为这只是从 unsigned char 转换为 char* 的一种情况。 但是,我没有设法以有效的方式做到这一点!

我正在做的是将数据作为无符号字符读入 C++ 程序 [64]。 然后需要通过 TCP 套接字将其传输到等待的 C# TcpListener(我也尝试在 linux 上使用netcatHurcules 进行侦听。

听众(无论我使用哪个)都没有收到任何有意义的信息!
如果我char* buffer2 = reinterpret_cast<char*>(buffer); 我收到了一些传输的信息,但这是无稽之谈,当我在调试期间检查 buffer2 时,它只包含一个“0”。

下面是一些使用我自己的 SocketClient_Winsock 类发送的精简 C++ 代码(更进一步)

#include "stdafx.h"
#include "SocketClient_Winsock.h"
#include <iostream>

using namespace std;
void GetData(unsigned char *fillme)
{

    // Fill the array!
    for (int a = 0; a < 64; a++)
    {
        fillme[a] = a;
    }

    printf("in GetData: \n");
    for (int a = 0; a < 64; a++)
        printf("%i, ", fillme[a]);
    printf("\n\n");


}


void SendData(char* sendme)
{
    printf("in SendData: \n");
    for (int a = 0; a < 64; a++)
        printf("%i, ", sendme[a]);
    printf("\n\n");

    SocketClient_Winsock sock("127.0.0.1"); // Default constructor 127.0.0.1:5000
    sock.Start();
    //sock.Send("Incoming!\n");
    sock.Send(sendme);
    //sock.Send("Done.");
    sock.Stop();


}

int _tmain(int argc, _TCHAR* argv[])
{
    // Create the buffer
    unsigned char buffer[64];

    printf("Before filling: \n"); // output
    for (int a = 0; a < 64; a++)
        printf("%i, ", buffer[a]);
    printf("\n\n");

    // Fill the buffer
    GetData(buffer);    

    printf("after filling: \n"); // output again
    for (int a = 0; a < 64; a++)
        printf("%i, ", buffer[a]);
    printf("\n\n");

    // Send data over TCP connection    
    SendData((char*)buffer);

    // Output
    printf("after sending: \n");
    for (int a = 0; a < 64; a++)
        printf("%i, ", buffer[a]);
    printf("\n\n");

    return 0;
}

这是 SocketClient_Winsock.h:

#pragma once
#define WIN32_LEAN_AND_MEAN

#include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
#include <string>
#include <algorithm>

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

#define DEFAULT_PORT "5000"
#define DEFAULT_BUFLEN 512
using namespace std;
class SocketClient_Winsock
{
private:

    WSADATA wsaData;
    SOCKET ConnectSocket = INVALID_SOCKET;
    struct addrinfo *result = NULL,
        *ptr = NULL,
        hints;
    //char *sendbuf = "this is a test"; // we expect this to be sent back from the class
    char recvbuf[DEFAULT_BUFLEN];
    int iResult;
    int recvbuflen = DEFAULT_BUFLEN;


    char* serverName;

public:
    SocketClient_Winsock();
    SocketClient_Winsock(char* servername);
    bool Start();
    int Stop();
    int Send(string);
    int Send(char*);
    int Send(unsigned char*);
    bool Recv();

    ~SocketClient_Winsock();
};

和 SocketClient_Winsock.cpp:

#include "stdafx.h"
#include "SocketClient_Winsock.h"
#include <iostream>
// From https://msdn.microsoft.com/en-us/library/windows/desktop/ms737591(v=vs.85).aspx
SocketClient_Winsock::SocketClient_Winsock()
{
    serverName = "127.0.0.1"; // Default to localhost
}
SocketClient_Winsock::SocketClient_Winsock(char * servername)
{
    serverName = servername;
    ConnectSocket = INVALID_SOCKET;
}
bool SocketClient_Winsock::Start() {

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

    ZeroMemory(&hints, sizeof(hints));
    hints.ai_family = AF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_protocol = IPPROTO_TCP;

    // Resolve the server address and port
    iResult = getaddrinfo(serverName, DEFAULT_PORT, &hints, &result);
    if (iResult != 0) {
        printf("getaddrinfo failed with error: %d\n", iResult);
        WSACleanup();
        return 1;
    }

    // Attempt to connect to an address until one succeeds
    for (ptr = result; ptr != NULL; ptr = ptr->ai_next) {

        // Create a SOCKET for connecting to server
        ConnectSocket = socket(ptr->ai_family, ptr->ai_socktype,
            ptr->ai_protocol);
        if (ConnectSocket == INVALID_SOCKET) {
            printf("socket failed with error: %ld\n", WSAGetLastError());
            WSACleanup();
            return 1;
        }

        // Connect to server.
        iResult = connect(ConnectSocket, ptr->ai_addr, (int)ptr->ai_addrlen);
        if (iResult == SOCKET_ERROR) {
            closesocket(ConnectSocket);
            ConnectSocket = INVALID_SOCKET;
            continue;
        }
        break;
    }

    freeaddrinfo(result);

    if (ConnectSocket == INVALID_SOCKET) {
        printf("Unable to connect to server!\n");
        WSACleanup();
        return 1;
    }


    return true;
};

int SocketClient_Winsock::Stop()
{
    // shutdown the connection since no more data will be sent
    iResult = shutdown(ConnectSocket, SD_SEND);
    if (iResult == SOCKET_ERROR) {
        printf("shutdown failed with error: %d\n", WSAGetLastError());
        closesocket(ConnectSocket);
        WSACleanup();
        return 1;
    }
    return 0;
};

// Send message to server
int SocketClient_Winsock::Send(char* msg)
{

    printf("during sending: \n");
    for (int a = 0; a < 64; a++)
        printf("%i, ", msg[a]);
    printf("\n\n");

    iResult = send(ConnectSocket, msg, (int)strlen(msg), 0);

    if (iResult == SOCKET_ERROR) {
        printf("send failed with error: %d\n", WSAGetLastError());
        closesocket(ConnectSocket);
        WSACleanup();
        return 1;
    }

    return 0;
};



int SocketClient_Winsock::Send(std::string msg)
{

    int iResult = send(ConnectSocket, msg.c_str(), msg.size(), 0);

    if (iResult == SOCKET_ERROR)
    {
        printf("send failed: %d\n", WSAGetLastError());
        Stop();
        return false;
    }

    return 0;
};

// Receive message from server
bool SocketClient_Winsock::Recv()
{
    char recvbuf[DEFAULT_BUFLEN];
    int iResult = recv(ConnectSocket, recvbuf, DEFAULT_BUFLEN, 0);

    if (iResult > 0)
    {

        std::string msg = std::string(recvbuf);

        msg.erase(msg.find_first_of("\n"), msg.length()); // remove all characters after /n
        std::cout << msg << std::endl;
        return true;
    }


    return false;
}
SocketClient_Winsock::~SocketClient_Winsock()
{
    // cleanup
    closesocket(ConnectSocket);
    WSACleanup();
}

和 C# 主机:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using System.Net;
using System.Net.Sockets;
namespace Receiver
{
    class Program
    {
        static void Main(string[] args)
        {
            // now listen:
            Int32 port = 5000;
            IPAddress localAddr = IPAddress.Parse("127.0.0.1");

            // TcpListener server = new TcpListener(port);
            TcpListener server = new TcpListener(localAddr, port);

            // Start listening for client requests.
            server.Start();

            // Buffer for reading data
            Byte[] bytes = new Byte[64];
            String data = null;

            // Enter the listening loop. 
            while(true) 
            {
                Console.Write("Waiting for a connection... ");

                // Perform a blocking call to accept requests. 
                // You could also user server.AcceptSocket() here.
                TcpClient client = server.AcceptTcpClient();            
                Console.WriteLine("Connected!");

                data = null;

                // Get a stream object for reading and writing
                NetworkStream stream = client.GetStream();

                int i;

                // Loop to receive all the data sent by the client. 
                while((i = stream.Read(bytes, 0, bytes.Length))!=0) 
                {   
                    // Translate data bytes to a ASCII string.
                    data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);


                    Console.WriteLine("Received: {0}", data);

                    // Process the data sent by the client.
                    data = data.ToUpper();

                    byte[] msg = System.Text.Encoding.ASCII.GetBytes(data);


                    // Send back a response.
                    //stream.Write(msg, 0, msg.Length);
                    //Console.WriteLine("Sent: {0}", data);            
                }

                // Shutdown and end connection
                client.Close();
            }

            Console.WriteLine("\nHit enter to continue...");

            Console.Read();
        }
    }
}

正如 MagikM18 在下面评论的那样,原始解决方案根本不是解决方案......只是一个错误的解决方法。

该错误在 C# 方面(我忽略了它,认为它来自 MSDN,不会有问题。不要那样做!)。 它正在获取我的数据并将其强制转换为 ASCII - 因此是无稽之谈。 如果我查看原始数据,一切都很好。

所以,我的发送数据现在看起来像这样:

int SocketClient_Winsock::Send(char* msg, int msgLength)
{
    iResult = send(ConnectSocket, msg, msgLength, 0);
    if (iResult == SOCKET_ERROR) {
        printf("send failed with error: %d\n", WSAGetLastError());
        closesocket(ConnectSocket);
        WSACleanup();
        return 1;
    }

    return 0;
};

并被调用: sock.Send((char*)buffer, BUFFER_LEN);

暂无
暂无

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

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