public void SendMsg(string text, string endPoint)
{
if (_listSocketInfo.Keys.Contains(endPoint) && _listSocketInfo[endPoint] != null)
{
_listSocketInfo[endPoint].socket.Send(Encoding.ASCII.GetBytes(text));
}
}
public void Stop()
{
_isListening = false;
foreach (SocketInfo s in _listSocketInfo.Values)
{
s.socket.Close();
}
}
public class SocketInfo
{
public Socket socket = null;
public byte[] buffer = null;
public byte[] msgBuffer = null;
public bool isConnected = false;
public SocketInfo()
{
buffer = new byte[1024 * 4];
}
}
}
public class SocketServerManager
public class SocketClientManager
{
public Socket _socket = null;
public EndPoint endPoint = null;
public SocketInfo socketInfo = null;
public bool _isConnected = false;
public delegate void OnConnectedHandler();
public event OnConnectedHandler OnConnected;
public event OnConnectedHandler OnFaildConnect;
public delegate void OnReceiveMsgHandler();
public event OnReceiveMsgHandler OnReceiveMsg;
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)
{
SocketInfo info = new SocketInfo();
try {
_socket.BeginReceive(info.buffer, 0, info.buffer.Length, SocketFlags.None, ReceiveCallback, info);
}
catch (SocketException ex)
{
_isConnected = false;
}
Thread.Sleep(100);
}
}