Form1.cs 3.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Drawing;
  6. using System.Linq;
  7. using System.Net;
  8. using System.Net.Sockets;
  9. using System.Text;
  10. using System.Threading.Tasks;
  11. using System.Windows.Forms;
  12. namespace WindowsFormsSocket
  13. {
  14. public partial class Form1 : Form
  15. {
  16. public Form1()
  17. {
  18. InitializeComponent();
  19. }
  20. //方法ConnectSocket用来实现连接远程的主机
  21. private static Socket ConnectSocket(string server, int port)
  22. {
  23. Socket socket = null; //实例化Socket对象,并初始化为空
  24. IPHostEntry iphostentry = null; //实例化IPHostEntry对象,并初始化为空,用来存储IP地址信息
  25. iphostentry = Dns.GetHostEntry(server);//获得主机信息
  26. //循环遍历得到的IP地址列表
  27. //因为一个主机可能有多个网卡,也就存在着多个IP地址
  28. foreach(IPAddress address in iphostentry.AddressList)
  29. {
  30. //使用指定的IP地址和端口号实例化IPEndPoint对象
  31. IPEndPoint IPEPoint = new IPEndPoint(address, port);
  32. //使用Socket的构造函数实例化一个Socket对象,以便用来连接远程主机
  33. Socket newSocket = new Socket(IPEPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
  34. newSocket.Connect(IPEPoint); //调用Connection方法尝试性的连接远程主机
  35. if (newSocket.Connected) //判断远程连接是否连接
  36. {
  37. socket = newSocket;
  38. break;
  39. }
  40. else
  41. {
  42. continue;
  43. }
  44. }
  45. return socket;
  46. }
  47. //获取指定服务器的主页面内容
  48. private static string SocketSendReceive(string server,int port)
  49. {
  50. //以GET方式,通过HTTP协议向服务端发送请求
  51. string request = "GET/HTTP/1.1\n主机:" + server + "\n连接:关闭\n";
  52. Byte[] btSend = Encoding.ASCII.GetBytes(request);
  53. Byte[] btReceived = new Byte[256];
  54. //调用自定义方法ConnectSocket,使用指定的服务器名和端口号实例化一个Socket对象
  55. Socket socket = ConnectSocket(server, port);
  56. if (socket == null)
  57. return ("连接失败!");
  58. //将请求发送到连接的服务器
  59. socket.Send(btSend,btSend.Length,0);
  60. int intContent = 0;
  61. string strContent = server + "上的默认页面内容:\n";
  62. do
  63. {
  64. //从绑定的Socket接收数据
  65. intContent = socket.Receive(btReceived, btReceived.Length, 0);
  66. //将接收到的数据转换为字符串类型
  67. strContent += Encoding.ASCII.GetString(btReceived, 0, intContent);
  68. }
  69. while (intContent > 0);
  70. return strContent;
  71. }
  72. private void button1_Click(object sender, EventArgs e)
  73. {
  74. string server = textBox1.Text; //指定主机名
  75. int port = Convert.ToInt32(textBox2.Text); //指定端口号
  76. //调用自定义方法SocketSendReceive获取指定主机的主页面内容
  77. string strContent = SocketSendReceive(server, port);
  78. MessageBox.Show(strContent);
  79. }
  80. }
  81. }