C#/ C ++ TCP / IP服务器/客户端收到错误的消息

时间:2017-02-28 11:16:02

标签: c# c++ tcp

我目前正在编写日志框架,我想将日志从C ++发送到C#服务器。

客户端成功连接到服务器,但是我从C ++发送到C#的字符串无法正确连接。

服务器代码(C#):

public void Receive()
    {
        try
        {
            mListener.Start();


            string data = null;

            while (true)
            {
                Console.WriteLine("Waiting for a connection... ");

                TcpClient client = mListener.AcceptTcpClient();
                Console.WriteLine("Connected!");

                data = null;

                NetworkStream stream = client.GetStream();

                byte[] bytes = new byte[client.SendBufferSize];

                int i;

                while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
                {
                    data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
                    Console.WriteLine("Received: {0}", data);
                }

                client.Close();

            }
        }
        catch (SocketException exc)
        {
            Console.WriteLine("SocketException: {0}", exc);
        }
        finally
        {
            mListener.Stop();
        }

    }

代码来自Microsoft CampleListener的示例。

客户端(C ++):

int sock = socket(AF_INET, SOCK_STREAM, 0);
struct sockaddr_in server;
if (sock < 0)
{
    std::cout << "Error creating socket" << std::endl;
    return false;
}
else
{
    memset(&server, 0, sizeof(server));

    server.sin_addr.s_addr = 0;
    server.sin_addr.s_addr = INADDR_ANY;
    server.sin_family = AF_INET;
    server.sin_port = htons(SERVER_PORT);

    if (connect(sock, (struct sockaddr*)&server, sizeof(server)) < 0)
    {
        std::cout << "Error while connecting" << std::endl;
        std::cout << "Error Code: " << errno << std::endl;
        return false;

    }
    else
    {

        ssize_t toSend = send(sock, &logtext, sizeof(logtext), 0);
        if (toSend == -1)
        {
            std::cout << "Error while sending" << std::endl;
            close(sock);
            return false;
        }
        else
        {
            std::cout << "Sent : [" << logtext << "]" << std::endl;
            close(sock);
            return true;
        }

    }

}

C ++程序的输出如下:
Loglevel:调试,记录:您好,我是测试! 发送:[嗨,我是考试!]
程序以退出代码结束:0

但是C#Server只接收以下内容:
等待连接...
连接!
收到:y ?? _?
等待联系......

当然我做错了什么......但我不知道它是什么......有人能帮助我吗?

最诚挚的问候 ShanBox

0 个答案:

没有答案