Asp.net Socket客户端(远程发送和接收数据)
程序员文章站
2022-06-04 23:06:40
复制代码 代码如下:/*************************************** * 对象名称: socketobj * 功能说明: 远程发送与接收 *...
复制代码 代码如下:
/***************************************
* 对象名称: socketobj
* 功能说明: 远程发送与接收
* 试用示例:
* using ec; //引用空间名
* string url = "218.75.111.74"; // url也可以是(http://www.baidu.com/)这种形式
* int port = 8000; //端口
* string sendstr = "domainname\n"; //组织要发送的字符串
* sendstr += "check\n";
* sendstr += "entityname:domains\n";
* sendstr += "domainname:" + this.textbox1.text + "\n";
* sendstr += ".\n";
* ebsocketobj o = new socketobj(); //创建新对象
* o.connection(url, port); //打开远程端口
* o.send(sendstr); //发送数据
* response.write(o.recev()); //接收数据
* o.dispose(); //销毁对象
**********************************************/
using system;
using system.io;
using system.net;
using system.net.sockets;
using system.text;
namespace ec
{
/// <summary>
/// socket 远程发送与接收
/// </summary>
public class socketobj
{
private networkstream ns;
private bool _alreadydispose = false;
#region 构造与释构
public ebsocketobj()
{
//
// todo: 在此处添加构造函数逻辑
//
}
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 成员
public void dispose()
{
dispose(true);
gc.suppressfinalize(this);
}
#endregion
#region 打开端口
/// <summary>
/// 打开端口
/// </summary>
/// <param name="url">url或者:ip地址</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 发送socket
/// <summary>
/// 发送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 收取信息
/// <summary>
/// 收取信息
/// </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
}
}