Copy Code code as follows:
/***************************************
* Object Name: Socketobj
* Function Description: Remote send and receive
* Trial Example:
* Using EC; Reference Space Name
* String url = "218.75.111.74"; URLs can also be (http://www.baidu.com/) This form
* int port = 8000; Port
* String sendstr = "domainname\n"; The string to be sent by the organization
* Sendstr + = "check\n";
* Sendstr + = "entityname:domains\n";
* Sendstr + = "DomainName:" + this. TextBox1.Text + "\ n";
* Sendstr + = ". \ n";
* Ebsocketobj o = new Socketobj (); Create a new object
* O.connection (URL, port); Open a remote port
* O.send (SENDSTR); Send data
* Response.Write (O.recev ()); Receive data
* O.dispose (); Destroying objects
**********************************************/
Using System;
Using System.IO;
Using System.Net;
Using System.Net.Sockets;
Using System.Text;
Namespace EC
{
<summary>
Socket remote Send and receive
</summary>
public class Socketobj
{
Private NetworkStream NS;
private bool _alreadydispose = false;
#region structure and its interpretation
Public Ebsocketobj ()
{
//
TODO: Add constructor logic here
//
}
Public ebsocketobj (string url, int port)
{
Connection (URL, port);
}
~ebsocketobj ()
{
Dispose ();
}
protected virtual void Dispose (bool isdisposing)
{
if (_alreadydispose) return;
if (isdisposing)
{
if (ns!= null)
{
Try
{
Ns. Close ();
}
catch (Exception E) {}
Ns. Dispose ();
}
}
_alreadydispose = true;
}
#endregion
#region IDisposable Members
public void Dispose ()
{
Dispose (TRUE);
Gc. SuppressFinalize (this);
}
#endregion
#region Open Port
<summary>
Open port
</summary>
<param name= "url" >url or: IP address </param>
<param name= "Port" ></param>
<returns></returns>
public virtual void Connection (string url, int port)
{
if (url = null | | | url = "") return;
if (Port < 0) return;
if (port. ToString () ==string. Empty) port = 80;
TcpClient TCP = NULL;
Try
{
TCP = new TcpClient (URL, port);
}
catch (Exception E)
{
throw new Exception ("Can ' t connection:" + URL);
}
THIS.NS = tcp. GetStream ();
}
#endregion
#region Send socket
<summary>
Send socket
</summary>
<param name= "NS" ></param>
<param name= "Message" ></param>
<returns></returns>
Public virtual bool Send (String message)
{
if (ns = null) return false;
if (message = = NULL | | message = = "") return false;
byte[] buf = Encoding.ASCII.GetBytes (message);
Try
{
Ns. Write (buf, 0, buf. Length);
}
catch (Exception E)
{
throw new Exception ("Send Date fail!");
}
return true;
}
#endregion
#region Collect information
<summary>
Collect information
</summary>
<param name= "NS" ></param>
<returns></returns>
public string Recev ()
{
if (ns = null) return null;
byte[] buf = new byte[4096];
int length = 0;
Try
{
Length = ns. Read (buf, 0, buf. Length);
}
catch (Exception E)
{
throw new Exception ("Receive data fail!");
}
Return Encoding.ASCII.GetString (buf, 0, length);
}
#endregion
}
}