C#和C ++套接字通信之间的兼容性 [英] Compatibility between C# and C++ Socket communication

查看:189
本文介绍了C#和C ++套接字通信之间的兼容性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我有一个用C#编写的客户端.当我尝试与用C#编写的服务器进行通信时,它工作正常.我试图使用同一客户端与用C ++编写的服务器进行通信,但它似乎无法正常工作当我说在客户端上连接时,服务器挂起时就建立了连接,一旦我关闭客户端,服务器就会弹出一个错误消息说客户端已关闭.这是我用来通过以下方式发送消息的代码客户:

Hi,

I have a client written in C#.It works fine when i try to communicate with a server written in C#.I''m trying to use the same client to communicate with a Server written in C++ and it doesn''t seem to work.The connection is made as the server hangs when i say connect on my client and as soon as i close the client the server pops up an error saying the client was closed.This is the code i''m using to send a message through the client:

public void SendMessage(String message)
{
    try
    {
        Object objData = message;

        byte[] byData = System.Text.Encoding.ASCII.GetBytes(objData.ToString());
        if (m_clientSocket != null)
        {
            m_clientSocket.Send(byData);
        }
    }
    catch (SocketException se)
    {
        throw new Exception(se.Message);
    }
}




是服务器无法理解客户端发送的消息格式的问题还是其他问题?

预先谢谢.




Is it a problem of the server not able to understand the format of the message that the client is sending or is it something else??

Thanks in advance.

推荐答案

啊,我一次遇到这个问题.

C ++/C#套接字兼容.根据定义,套接字用于在实际上可能在不同体系结构的不同计算机上并以不同语言编码的应用程序之间进行通信.套接字旨在促进它们之间的数据传递.

也就是说,问题通常是应用程序之间的邮件框架"和/或期望不匹配".您的代码片段没有显示任何消息,该消息指示所传递的字符串消息"的长度.那么接收者如何知道要接收多少字节数据才能知道消息是否完整?

由于C#字符串对象*不*包含NULL字符,但是C ++ CString对象包含NULL字符,因此一个合理的猜测是接收者仍在等待NULL终止传入的字符串.

另一种可能性是UNICODE. C#字符串是unicode,结果字节数组将为字符串中的每个字符"都有两个字节".如果您的C ++应用程序未使用unicode,则它将在数据流中每隔一个字符看到NULL.

您应该检查接收器,看看是否有这些常见问题.
Ah, I had this problem once.

C++ / C# Sockets are compatible. Sockets, by definition, are for communicating between applications that may, in fact, be on different computers of different architectures and coded in different languages. Sockets are intended to facilite data passing between them.

That said, the issue is often "Messasge Framing" and/or "mismatched expectations" between the applications. Your code fragment does not show any message that indicates the length of the "String message" being passed. So how is the receiver to know how many bytes of data to receive to know that the message is complete?

Since C# string objects do *not* include a NULL character but the C++ CString objects do, one reasonable guess is that the receiver is still waiting for the NULL to terminate the incoming string.

One other possibility is UNICODE. C# strings are unicode and the resultant byte array will have two "bytes" for every "character" in the string. If your C++ application is not using unicode, then it will see a NULL every other character in the data stream.

You should check your receiver to see if you have these common issues.


这篇关于C#和C ++套接字通信之间的兼容性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆