【问题标题】:C# Socket connection doesn't workC# Socket 连接不起作用
【发布时间】:2014-02-26 22:32:03
【问题描述】:

我正在尝试创建代码以将 TCP 消息发送到服务器。

当我在这段代码中使用 AutoIT 脚本语言时:

Example()

Func Example()

Local $ConnectedSocket, $szData

Local $szIPADDRESS = "10.200.0.104"

Local $nPORT = 1040

; Start The TCP Services

TCPStartup()

; Initialize a variable to represent a connection

$ConnectedSocket = -1

;Attempt to connect to SERVER at its IP and PORT 1040


$ConnectedSocket = TCPConnect($szIPADDRESS, $nPORT)

; If there is an error... show it

If @error Then
MsgBox(4112, "Error", "TCPConnect failed with WSA error: " & @error)


Else


$szData="0x0021601FA10706052B0C00815ABE14281206072B0C00821D8148A007A0050303000800000DA20B0201013006020200D30500"

TCPSend($ConnectedSocket, $szData)

EndIf

EndFunc;==>Example

工作正常,但我需要用 C# 编写相同的代码。我尝试这样做:

private static byte[] MessageToByteArray(string message, Encoding encoding)
        {
            var byteCount = encoding.GetByteCount(message);
            if (byteCount > byte.MaxValue)
                throw new ArgumentException("Message size is greater than 255 bytes in the provided encoding");
            var byteArray = new byte[byteCount + 1];
            byteArray[0] = (byte)byteCount;
            encoding.GetBytes(message, 0, message.Length, byteArray, 1);
            return byteArray;
        }

        public static void Main(string[] args)
        {
            const string message = "0x0021601FA10706052B0C00815ABE14281206072B0C00821D8148A007A0050303000800000DA20B0201013006020200D30500";
            var byteArray = MessageToByteArray(message, Encoding.ASCII);

            Socket m_socClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);

            System.Net.IPAddress ipAdd = System.Net.IPAddress.Parse("10.200.0.104");
            System.Net.IPEndPoint remoteEP = new IPEndPoint(ipAdd, 1040);
            m_socClient.Connect(remoteEP);

            try
            {

                m_socClient.Send(byteArray);
            }
            catch (SocketException se)
            {
                Console.WriteLine(se.Message.ToString());
            }



        }

但是这段代码不起作用。服务器在他收到命令时显示。使用 C# 代码,服务器显示已连接但命令未执行。

【问题讨论】:

  • 为什么 c# 代码有长度前缀而 AutoIT 脚本没有?
  • 服务器是否也显示何时收到命令或何时执行命令?大概发送一个无效的数据包不会执行命令

标签: c# sockets message send


【解决方案1】:

您确定必须在长度前加上前缀吗?

byteArray[0] = (byte)byteCount;
encoding.GetBytes(message, 0, message.Length, byteArray, 1);

通常你有一个以 null 结尾的字符串:

encoding.GetBytes(message, 0, message.Length, byteArray, 0);
byteArray[byteArray.Length - 1] = (byte)'\0';

【讨论】:

  • 如果数据包是固定大小的,也可能只是字符串
  • 是的。如果它是固定大小,我会在最后使用零填充。
猜你喜欢
  • 2017-03-08
  • 2017-09-02
  • 2017-01-24
  • 2023-04-04
  • 1970-01-01
  • 1970-01-01
  • 2015-03-09
  • 1970-01-01
  • 2018-09-03
相关资源
最近更新 更多