using System;using System.Data;using System.Configuration;using System.Collections;using System.Web;using System.Web.Security;using System.Web.UI;using System.Web.UI.WebControls;using System.Web.UI.WebControls.WebParts;using System.Web.UI.HtmlControls;using System.Net.Sockets;using System.Threading;using System.Net;using System.Text;using System.IO;namespace SocketRun{ // State object for receiving data from remote device. public class StateObject { // Client socket. public Socket workSocket = null; // Size of receive buffer. public const int BufferSize = 256; // Receive buffer. public byte[] buffer = new byte[BufferSize]; // Received data string. public StringBuilder sb = new StringBuilder(); } public partial class _Default : System.Web.UI.Page { // ManualResetEvent instances signal completion private static ManualResetEvent allDone = new ManualResetEvent(false); private static ManualResetEvent sendDone = new ManualResetEvent(false); private static ManualResetEvent receiveDone = new ManualResetEvent(false); // Received data string. private StringBuilder sb = new StringBuilder(); //取得预保存的文件名 private string fileName = @"E:\WebLib\ReadXML\TestResults.txt"; protected void Page_Load(object sender, EventArgs e) { string host = @"219.238.192.100"; int port = 34200; string Request = "kw=日本人&page=1"; #region 测试数据 //string host = @"http://www.um114.com"; //int port = 8000; //Socket tempSocket = new Socket(IPAddress.Parse(host).AddressFamily, // SocketType.Stream, // ProtocolType.Tcp); //tempSocket.Connect(IPAddress.Parse(host), port); //if (tempSocket.Connected) // this.lbInfo.Text = "Ok"; #endregion try { StartClient(host, port, Request); } catch (Exception ex) { this.lbInfo.Text = ex.Message; } } /// <summary> /// 发起一次异步连接尝试 /// </summary> /// <param name="ar"></param> private void ConnectCallback(IAsyncResult ar) { allDone.Set(); Socket s = (Socket)ar.AsyncState; s.EndConnect(ar); } /// <summary> /// 发送函数 /// </summary> /// <param name="client"></param> /// <param name="data"></param> private void Send(Socket client, string data) { // Convert the string data to byte data using Default encoding. byte[] byteData = Encoding.Default.GetBytes(data); // Begin sending the data to the remote device. client.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), client); } /// <summary> /// 接受函数 /// </summary> /// <param name="client"></param> private void Receive(Socket client) { try { // Create the state object. StateObject state = new StateObject(); state.workSocket = client; // Begin receiving the data from the remote device. client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReceiveCallback), state); } catch { } } /// <summary> /// 发送异步 /// </summary> /// <param name="ar"></param> private void SendCallback(IAsyncResult ar) { try { // Retrieve the socket from the state object. Socket client = (Socket)ar.AsyncState; // Complete sending the data to the remote device. int bytesSent = client.EndSend(ar); // Signal that all bytes have been sent. sendDone.Set(); } catch { } } /// <summary> /// 接受异步 /// </summary> /// <param name="ar"></param> private void ReceiveCallback(IAsyncResult ar) { // The response from the remote device. string response = string.Empty; try { // Retrieve the state object and the client socket // from the asynchronous state object. StateObject state = (StateObject)ar.AsyncState; Socket client = state.workSocket; // Read data from the remote device. int bytesRead = client.EndReceive(ar); if (bytesRead > 0) { // There might be more data, so store the data received so far. state.sb.Append(Encoding.Default.GetString(state.buffer, 0, bytesRead)); // Get the rest of the data. client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReceiveCallback), state); } else { // All the data has arrived; put it in response. if (state.sb.Length > 1) { response = state.sb.ToString(); } //将所读取的字符串转换为字节数组 byte[] content = Encoding.Default.GetBytes(response); try { //创建文件流对象实例 FileStream fs = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite); //写入文件 fs.Write(content, 0, content.Length); fs.Close(); fs.Dispose(); } catch (Exception ex) { this.lbInfo.Text = "文件创建/写入错误:" + ex.Message; } // Signal that all bytes have been received. receiveDone.Set(); } } catch { } } /// <summary> /// Asynchronous connect using the host name /// </summary> /// <param name="host"></param> /// <param name="port"></param> private Socket ConnectSocket(string host, int port) { Socket s = null; #region 测试数据 //IPHostEntry hostEntry = null; //try //{ // hostEntry = Dns.GetHostEntry(host); //} //catch (Exception ex) //{ // this.lbInfo.Text = ex.Message; // return null; //} //IPAddress address = hostEntry.AddressList[0]; //IPEndPoint ipe = new IPEndPoint(address, port); #endregion IPEndPoint ipe = new IPEndPoint(IPAddress.Parse(host), port); Socket tempSocket = new Socket(ipe.Address.AddressFamily, SocketType.Stream, ProtocolType.Tcp); allDone.Reset(); try { tempSocket.BeginConnect(ipe, new AsyncCallback(ConnectCallback), tempSocket); } catch (Exception ex) { this.lbInfo.Text = ex.Message; } // wait here until the connect finishes. // The callback sets allDone. allDone.WaitOne(); if (tempSocket.Connected) { s = tempSocket; } return s; } /// <summary> /// This method requests the home page content for the specified server. /// </summary> /// <param name="server"></param> /// <param name="port"></param> /// <returns></returns> private void StartClient(string server, int port, string Request) { try { // Create a socket connection with the specified server and port. Socket s = ConnectSocket(server, port); if (s == null) return;//("Connection failed"); //设置为非阻塞状态 s.Blocking = false; // //向主机发送请求 // Send test data to the remote device. Send(s, Request); sendDone.WaitOne(); // Receive the response from the remote device. Receive(s); receiveDone.WaitOne(); s.Blocking = true; //禁用Socket s.Shutdown(SocketShutdown.Both); //关闭Socket s.Close(); } catch (Exception e) { } } }}

评论