使用 Socket 类向 HTTP 服务器发送数据和接收响应。
2014-04-28 12:38
477 查看
using System; using System.Text; using System.IO; using System.Net; using System.Net.Sockets; public class GetSocket { private static Socket ConnectSocket(string server, int port) { Socket s = null; IPHostEntry hostEntry = null; // Get host related information. hostEntry = Dns.GetHostEntry(server); // Loop through the AddressList to obtain the supported AddressFamily. This is to avoid // an exception that occurs when the host IP Address is not compatible with the address family // (typical in the IPv6 case). foreach(IPAddress address in hostEntry.AddressList) { IPEndPoint ipe = new IPEndPoint(address, port); Socket tempSocket = new Socket(ipe.AddressFamily, SocketType.Stream, ProtocolType.Tcp); tempSocket.Connect(ipe); if(tempSocket.Connected) { s = tempSocket; break; } else { continue; } } return s; } // This method requests the home page content for the specified server. private static string SocketSendReceive(string server, int port) { string request = "GET / HTTP/1.1\r\nHost: " + server + "\r\nConnection: Close\r\n\r\n"; Byte[] bytesSent = Encoding.ASCII.GetBytes(request); Byte[] bytesReceived = new Byte[256]; // Create a socket connection with the specified server and port. Socket s = ConnectSocket(server, port); if (s == null) return ("Connection failed"); // Send request to the server. s.Send(bytesSent, bytesSent.Length, 0); // Receive the server home page content. int bytes = 0; string page = "Default HTML page on " + server + ":\r\n"; // The following will block until te page is transmitted. do { bytes = s.Receive(bytesReceived, bytesReceived.Length, 0); page = page + Encoding.ASCII.GetString(bytesReceived, 0, bytes); } while (bytes > 0); return page; } public static void Main(string[] args) { string host; int port = 80; if (args.Length == 0) // If no server name is passed as argument to this program, // use the current host name as the default. host = Dns.GetHostName(); else host = args[0]; string result = SocketSendReceive(host, port); Console.WriteLine(result); } }
相关文章推荐
- Python中使用socket发送HTTP请求数据接收不完整问题解决方法
- Python中使用socket发送HTTP请求数据接收不完整问题解决方法
- Java网络编程从入门到精通(13):使用Socket类接收和发送数据
- 安卓与串口服务器互联发送数据报文与接收数据报DatagramSocket.receive(参数体)接收不到数据报文
- 前台使用$.ajax()发送json数据,服务器响应后返回json数据实例(struts2+json+action)
- Windows 和 Linux下使用socket下载网页页面内容(可设置接收/发送超时)的代码(用socket解释http,不错)
- Android使用HttpUrlConnection请求服务器发送数据详解
- socket服务器发送大数据,客户端循环接收
- Android使用HttpPost向服务器发送Json数据
- httpclient使用post方式发送json数据,以及服务端的接收
- 使用socket读取服务器发送的数据问题
- HttpURLConnection 向服务器发送post和get请求 并接收响应
- 使用angularjs的$http.post异步提交数据时,服务器接收不了的问题
- Android使用HttpPost向服务器发送Json数据
- HttpClient 使用get方式发送数据到服务器并下载服务器文件
- 简单socket服务(三)实现多客户端向服务器发送数据并保证服务器接收到数据
- Android使用HttpPost向服务器发送Json数据
- 使用DatagramSocket发送、接收数据(Socket之UDP套接字)
- Java网络编程从入门到精通(13):使用Socket类接收和发送数据
- Ajax 使用XMLHttpRequest对象发送数据和接收处理XML源代码