[英]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.