public class Client
{
private string _ip = string.Empty;
private int _port = 0;
private Socket _socket = null;
private byte[] _buffer = new byte[1024 * 1024 * 2];
//创建事件将数据传输到UI
Informations _informations;
//监听Task
private Task _task;
//Task Token
private static CancellationTokenSource cancelTokenSource = new CancellationTokenSource();
public Client(string ip,int port,Informations informations)
{
_ip = ip;
_port = port;
_informations = informations;
}
public Client( int port, Informations informations)
{
_port = port;
_ip = IPAddress.Any.ToString();
_informations = informations;
}
//开始监听
public void StartClient()
{
try
{
//创建套子
_socket = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
//创建连接目标的IP
IPAddress address = IPAddress.Parse( _ip );
//创建连接目标的端点
IPEndPoint iPEndPoint = new IPEndPoint(address, _port);
//连接端点
_socket.Connect(iPEndPoint);
_informations.Invoke("连接服务器成功");
//开始监听目标的信息
Task.Factory.StartNew(() => ReceiveMsg(), cancelTokenSource.Token);
}
catch (Exception ex)
{
_socket.Shutdown(SocketShutdown.Both);
_socket.Close();
_informations.Invoke(ex.Message);
}
}
//接收信息
private void ReceiveMsg()
{
while (true)
{
Byte[] buffer = new Byte[1024 * 1024 * 2];
int length = _socket.Receive(buffer);
if (buffer.Length > 0)
{
_informations.Invoke($"接收服务器 {_ip},消息:{Encoding.UTF8.GetString(buffer,0, length)}");
}
}
}
//关闭连接
public void CloseConnection()
{
cancelTokenSource.Cancel();
_socket.Close();
}
//发送信息
public void SendMsg(string a)
{
string sendMessage = $"{DateTime.Now.ToString()}: a";
_socket.Send(Encoding.UTF8.GetBytes(a));
}
}