乔山办公网我们一直在努力
您的位置:乔山办公网 > word文档 > word向程序发送命令时出现问题-C井怎样通过ip和端口向一台设备发送指令

word向程序发送命令时出现问题-C井怎样通过ip和端口向一台设备发送指令

作者:乔山办公网日期:

返回目录:word文档

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using System.Net;
  5. using System.Net.Sockets;
  6. namespace Client
  7. {
  8. class Program
  9. {
  10. static void Main(string[] args)
  11. {
  12. try
  13. {
  14. int port = 2000;
  15. string host = "127.0.0.1";
  16. ///创建终结点EndPoint
  17. IPAddress ip = IPAddress.Parse(host);
  18. //IPAddress ipp = new IPAddress("127.0.0.1");
  19. IPEndPoint ipe = new IPEndPoint(ip, port);//把ip和端口转化为IPEndpoint实例
  20. ///创建socket并连接到服务器
  21. Socket c = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//创建Socket
  22. Console.WriteLine("Conneting…");
  23. c.Connect(ipe);//连接到服务器
  24. ///向服务器发送信息
  25. string sendStr = "hello!This is a socket test";
  26. byte[] bs = Encoding.ASCII.GetBytes(sendStr);//把字符串编码为字节
  27. Console.WriteLine("Send Message");
  28. c.Send(bs, bs.Length, 0);//发送信息
  29. ///接受从服务器返回的信息
  30. string recvStr = "";
  31. byte[] recvBytes = new byte[1024];
  32. int bytes;
  33. bytes = c.Receive(recvBytes, recvBytes.Length, 0);//从服务器端接受返回信息
  34. recvStr += Encoding.ASCII.GetString(recvBytes, 0, bytes);
  35. Console.WriteLine("client get message:{0}", recvStr);//显示服务器返回信息
  36. ///一定记着用完socket后要关闭
  37. c.Close();
  38. }
  39. catch (ArgumentNullException e)
  40. {
  41. Console.WriteLine("argumentNullException: {0}", e);
  42. }
  43. catch (SocketException e)
  44. {
  45. Console.WriteLine("SocketException:{0}", e);
  46. }
  47. Console.WriteLine("Press Enter to Exit");
  48. }
  49. }
  50. }

相关阅读

关键词不能为空
极力推荐

ppt怎么做_excel表格制作_office365_word文档_365办公网