C#套接字连接不起作用

时间:2014-02-03 12:22:24

标签: c# sockets message send

我正在尝试创建一个代码来向服务器发送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#代码,服务器显示已连接但命令未执行。

1 个答案:

答案 0 :(得分:0)

你确定你必须加上长度的前缀吗?

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

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

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