public void StartTcpClient(Model.TcpClientModel model) { ClientModel = model; // 解析并开始建立客户端 int port; IPEndPoint remoteEndPoint; try { port = int.Parse(model.RemotePort); remoteEndPoint = new IPEndPoint(IPAddress.Parse(model.RemoteAddress), port); Client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); Client.Connect(remoteEndPoint); model.AddClientState("客户端建立成功..."); } catch (Exception) { model.AddClientState("建立客户端失败"); return; } try { int rece; while (true) { rece = Client.Receive(data); if (rece == 0) { throw new Exception("Server Stop"); } model.AddReceiveAndSendMessage("接收 -->> " + Encoding.UTF8.GetString(data, 0, rece)); } }catch (Exception) { model.AddClientState("接收数据出错,关闭客户端"); if (Client.Connected) { Client?.Shutdown(SocketShutdown.Both); Client?.Close(); } } }
/// <summary> /// 构造函数 /// </summary> public TcpClientViewModel() { TcpClientModelInstance = new Model.TcpClientModel(); TcpClientInstance = new TcpPart.TcpClient(); }