首页 > 代码库 > C#socket通讯服务器(连接状态监控)

C#socket通讯服务器(连接状态监控)

class SocketServerManager
{
public delegate void ConnectStateEventHandler();
public event ConnectStateEventHandler ConnectedEvent;//客户端连线
public event ConnectStateEventHandler DisConnectedEvent;//客户端掉线

public delegate void ReceiveMsgEventHandler(byte[] order);
public event ReceiveMsgEventHandler ReceiveMsgEvent;

static Socket _socket = null;
static IPEndPoint iep = null;
static bool isListening = false;
static bool isConnected = false;
static Dictionary<EndPoint, Socket> dic = null;
static EndPoint ep = null;

public SocketServerManager(string strIP,int port)
{
_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPAddress IP = IPAddress.Parse(strIP.Trim());
iep = new IPEndPoint(IP, port);
dic=new Dictionary<EndPoint,Socket>();
}

public void Start()
{
_socket.Bind(iep);
isListening = true;
Thread t = new Thread(Listen);
t.IsBackground = true;
t.Start();
}

private void Listen()
{
while (isListening)
{
_socket.Listen(0);
Socket newsocket = _socket.Accept();
if (ConnectedEvent != null) ConnectedEvent();
ep = newsocket.RemoteEndPoint;
dic.Add(ep, newsocket);
isConnected = true;
Thread t1 = new Thread(ReceiveMsg);
t1.IsBackground = true;
t1.Start();
}
}

private void ReceiveMsg()
{
while (isConnected)
{
byte[] buffer=new byte[32];
int count = dic[ep].Receive(buffer);
if (count > 0&&ReceiveMsgEvent != null)
{
ReceiveMsgEvent(buffer);
}
if (!IsSocketConnected(dic[ep]) && DisConnectedEvent != null)
{
DisConnectedEvent();
isConnected = false;
}
Thread.Sleep(200);
}
}

public void SendMsg(byte[] order)
{
dic[ep].Send(order,order.Length,SocketFlags.None);
}

private bool IsSocketConnected(Socket s)
{
return !((s.Poll(1000, SelectMode.SelectRead) && (s.Available == 0)) || !s.Connected);
}
}

C#socket通讯服务器(连接状态监控)