using System; using System.Collections.Generic; using System.Text; using System.Net; using System.Net.Sockets; using System.Threading; using SocketProgram; namespace TcpClientLib { public class TcpClient { private byte[] buffer = new byte[1024]; private IPEndPoint ipEndPoint; private Socket mClientSocket; private bool isConnected = false; private int sleepTime = 5000; private static readonly string logPath = "../log/Client.log"; public TcpClient(string ip,int port,int sleepTime) { this.ipEndPoint = new IPEndPoint(IPAddress.Parse(ip), port); if(sleepTime > 500) { this.sleepTime = sleepTime; } mClientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); } public void Start() { int num = 0; while (true) { if (!this.isConnected) { try { mClientSocket.Connect(this.ipEndPoint); this.isConnected = true; Console.WriteLine("连接成功"); SocketClass.WriteLog(logPath, SocketClass.GetNowTimeStr() + "连接成功"); var mReceiveThread = new Thread(this.ReceiveMessage); mReceiveThread.Start(); } catch (Exception e) { string estr = e.ToString(); Console.WriteLine(estr); SocketClass.WriteLog(logPath, estr); this.isConnected = false; } } else { string timeStr = SocketClass.GetNowTimeStr(); string sendStr = timeStr + num; mClientSocket.Send(Encoding.UTF8.GetBytes(sendStr)); string logstr = timeStr + ":send:" + num++; Console.WriteLine(logstr); } Thread.Sleep(this.sleepTime); } } private void ReceiveMessage() { while (true) { try { int receiveLength = this.mClientSocket.Receive(buffer); string serverMessage = Encoding.UTF8.GetString(buffer, 0, receiveLength); string logstr = SocketClass.GetNowTimeStr() + ":cl_recv:" + serverMessage; Console.WriteLine(logstr); SocketClass.WriteLog(logPath, logstr); } catch (Exception e) { this.mClientSocket.Shutdown(SocketShutdown.Both); this.mClientSocket.Close(); this.isConnected = false; string logstr = SocketClass.GetNowTimeStr() + ":" + e.ToString(); Console.WriteLine(logstr); SocketClass.WriteLog(logPath, logstr); this.mClientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); break; } } } } }