public SocketClientManager(string ip, int port)
{
IPAddress _ip = IPAddress.Parse(ip);
endPoint = new IPEndPoint(_ip, port);
_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
}
public void Start()
{
_socket.BeginConnect(endPoint, ConnectedCallback, _socket);
_isConnected = true;
Thread socketClient = new Thread(SocketClientReceive);
socketClient.IsBackground = true;
socketClient.Start();
}
public void SocketClientReceive()
{
while (_isConnected)
{
try {
_socket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, ReceiveCallback, buffer);
}
catch (SocketException ex)
{
_isConnected = false;
}
Thread.Sleep(100);
}
}
public void ReceiveCallback(IAsyncResult ar)
{
}
}
public class SocketClientManager
主要记住的是,客户端是监听Socket是固定的,是监听绑定地址的,每当有新的连接访问,则开启新的线程与之进行交互,而客户端只简单实现与服务端交互,服务端则只有一个。
Socket的进行发送与接收,一般是通过异步方法BeginReceive和BeginSend进行处理,方法一般带有回调函数,用于执行操作之后的处理。
还有就是连接的关闭,每关闭一个连接,先要结束在Socket所在的线程方法,我这里的处理是停止掉死循环的函数调用,每当线程所在函数执行完毕,则线程自动销毁。之后就是关闭所连接的socket。
下面是我程序的完整实现,为了方便socket的管理,我把服务器的所有与客户端对话的Socket统一用字典管理,并封装在SocketInfo的内部类中,消息的发送与接收必须先找到该连接socket。
最后就是界面的调用,完成Socket的网络消息交互。
下面是具体的实现及源码:
public class SocketManager
{
public Dictionary<string,SocketInfo> _listSocketInfo = null;
Socket _socket = null;
public SocketInfo socketInfo = null;
EndPoint _endPoint = null;
bool _isListening = false;
int BACKLOG = 10;
public delegate void OnConnectedHandler(string clientIP);
public event OnConnectedHandler OnConnected;
public delegate void OnReceiveMsgHandler(string ip);
public event OnReceiveMsgHandler OnReceiveMsg;
public event OnReceiveMsgHandler OnDisConnected;
public SocketManager(string ip, int port)
{
_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPAddress _ip = IPAddress.Parse(ip);
_endPoint = new IPEndPoint(_ip, port);
_listSocketInfo = new Dictionary<string, SocketInfo>();
}
public void Start()
{
_socket.Bind(_endPoint); //绑定端口
_socket.Listen(BACKLOG); //开启监听
Thread acceptServer = new Thread(AcceptWork); //开启新线程处理监听
acceptServer.IsBackground = true;
_isListening = true;
acceptServer.Start();
}