使用 Socket 类向 HTTP 服务器发送数据和接收响应。
来源:互联网 发布:mac 隐藏文件夹显示 编辑:程序博客网 时间:2024/04/30 13:19
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); }}
0 0
- 使用 Socket 类向 HTTP 服务器发送数据和接收响应。
- 使用Socket类接收和发送数据
- 使用Socket类接收和发送数据
- 模拟浏览器向服务器发送和接收数据
- HttpURLConnection 向服务器发送post和get请求 并接收响应
- C#使用Socket发送和接收TCP数据示例
- 安卓向服务器发送数据和服务器接收数据全过程
- android平台通过socket向C++服务器端发送数据和接收数据的相关问题
- android平台通过socket向C++服务器端发送数据和接收数据的相关问题
- android用socket向服务器发送和接收消息 【转自网易闯京城的博客】
- 向ESB发送和接收数据
- Java网络编程从入门到精通(13):使用Socket类接收和发送数据
- Java网络编程(13):使用Socket类接收和发送数据
- Java网络编程从入门到精通(13):使用Socket类接收和发送数据
- Java网络编程从入门到精通(13):使用Socket类接收和发送数据
- Java网络编程从入门到精通(13):使用Socket类接收和发送数据
- 异步 SOCKET 编程 - 发送和接收数据
- 异步 SOCKET 编程 - 发送和接收数据
- Sap Tree Control
- pymogo数据库连接错误
- 树莓派玩家需要的X条核心品格
- 最大似然估计方法
- 欧拉错排公式
- 使用 Socket 类向 HTTP 服务器发送数据和接收响应。
- 链表排序
- 光学变焦:拍照手机的下一个卖点?
- Android性能优化工具dmtracedump
- MySQL 获得当前日期时间(以及时间的转换)
- 小菜鸟最近刚理解透的两类易错知识点
- Bitmap优化
- apache mod_rewrite
- 贝叶斯定理决策规则及Bayes思想总结