簡體   English   中英

C#套接字連接不起作用

[英]C# Socket connection doesn't work

我正在嘗試創建代碼以將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#代碼,服務器顯示已連接,但命令未執行。

確定要為長度加上前綴嗎?

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';

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM