3.2.3 C#代码实现

创建一个windows控制台程序,保存为helloworld.cs,编辑代码如下:

using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Linq; using System.Text; using System.Net; using System.Net.Sockets; namespace helloworld { class Program { static void Main(string[] args) { string serverIP = "10.129.250.151";//设备地址 int serverPort = 80;//设备web远程端口 IPAddress serverIPAddress; TcpClient tcpClient; serverIPAddress = IPAddress.Parse(serverIP); tcpClient = new TcpClient(); tcpClient.Connect(serverIPAddress, serverPort); if(tcpClient==null) { Console.WriteLine("failed to connect server, please try it again!\n"); } else { //获取一个和服务器关联的网络流 NetworkStream networkStream = tcpClient.GetStream(); //给服务器发送数据 string apixml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Control attribute=\"Query\">\n<DeviceInfo/>\n</Control>\n"; string httpstr = string.Format("POST /xml HTTP/1.1\nContent-Type:text/html\nHost:10.129.250.151:8080\nContent-Length: {0}\n\n{1}",apixml.Length,apixml); Console.WriteLine("send: "+httpstr+"\n"); byte[] buf = Encoding.UTF8.GetBytes(httpstr); networkStream.Write(buf,0,buf.Length); networkStream.Flush(); //读取服务器返回的信息 byte[] recvbuf = new byte[1600]; networkStream.Read(recvbuf,0,recvbuf.Length); networkStream.Flush(); string resultstr = Encoding.UTF8.GetString(recvbuf); Console.WriteLine("recv: "+resultstr+"\n"); Console.WriteLine("Press any key to exit."); Console.ReadKey(); } } } }


编译生成helloworld.exe,按F5运行,正常看到发送和返回结果,测试可用。

results matching ""

    No results matching ""