发现.NET版人气不行,发个文章大家看看
.NET中的TcpListener很简单,但用起来似乎有点不爽,操作起来步骤太多了,于是便有了下文,对TcpListener的简单封装...
希望大家顶个人气!:loveliness:
共有二个文件组成
ServerSocket.cs:
using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Collections;
namespace CXP.Net
{
public class ServerSocket : TcpListener
{
private ArrayList socketArr = new ArrayList();
private bool isRunning = false; //是否正在监听
private ClientThread clientThread = null;
#region 构造
public ServerSocket(int port) : base(SocketCommon.GetLocalIP(InternetType.Lan), port) { }
public ServerSocket(IPAddress ip, int port) : base(ip, port) { }
public ServerSocket(IPEndPoint ipep) : base(ipep) { }
#endregion
#region 方法
/// <summary>
/// 开始监听端口
/// </summary>
public void Listen(ClientThread ct)
{
if (this.isRunning) return;
this.clientThread = ct;
this.Start();
Thread thread = new Thread(new ThreadStart(WaitConnect));
thread.Start(); //开始监听
this.isRunning = true;
}
/// <summary>
/// 停止监听
/// </summary>
public new void Stop()
{
if (this.isRunning)
{
base.Stop();
this.isRunning = false;
//关闭所有已经接受的连接
foreach (object o in this.socketArr)
{
((TcpClient)o).Close();
}
}
}
/// <summary>
/// 等待连接
/// </summary>
private void WaitConnect()
{
while (isRunning)
{
if (this.Pending())
{
try
{
TcpClient client = this.AcceptTcpClient();
this.socketArr.Add(client); //添加客户端
this.clientThread(client);
}
catch
{
}
}
Thread.Sleep(300);
}
Thread.CurrentThread.Abort(); //结束当前线程
}
#endregion
}
}
SocketCommon.cs:
using System;
using System.Net;
using System.Net.Sockets;
namespace CXP.Net
{
class SocketCommon
{
/// <summary>
/// 获取本机IP地址
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
public static IPAddress GetLocalIP(InternetType type)
{
IPAddress ip = Dns.GetHostEntry(Dns.GetHostName()).AddressList[(int)type];
return ip;
}
}
/// <summary>
/// 表示网络IP类型
/// </summary>
public enum InternetType
{
Lan = 0, //局域网
Wan = 1 //广域网
}
/// <summary>
/// TcpClient线程委托
/// </summary>
/// <param name="client"></param>
public delegate void ClientThread(TcpClient client);
}
(突然发现不能发附件,看来DEMO不能发布了...:L )
这些都是简单的封装,有什么不对的地方,请大家指出,
下次再发个封装TcpClient的类...:lol
转载于:https://www.cnblogs.com/boxwork/archive/2012/08/22/2651726.html