using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections;
using System.Net.Sockets;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Timers;
namespace SocketProject
{
class TcpClient
{
private int port;
private string name;
private List<string> stringList = new List<string>();
private static readonly TcpClient singleInstance = new TcpClient();
Socket tcpClient;
private Timer timer;
//单例模式
public static TcpClient GetInstance
{
get
{
return singleInstance;
}
}
public TcpClient()
{
}
public void TryToConnet(string Name, int Port)
{
port = Port;
name = Name;
if (null != timer)
{
timer.Stop();
}
if (null != tcpClient)
{
tcpClient.Close();
tcpClient = null;
}
tcpClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
tcpClient.BeginConnect(name, port, Connect, null);
}
private void Connect(IAsyncResult ar)
{
try
{
tcpClient.EndConnect(ar);
if (tcpClient.Connected)
{
Console.WriteLine($"Connected Succeed");
if (timer != null)
{
timer.Start();
}
else
{
//设置定时间隔(毫秒为单位)
int interval = 500;
timer = new System.Timers.Timer(interval);
//设置执行一次(false)还是一直执行(true)
timer.AutoReset = true;
//设置是否执行System.Timers.Timer.Elapsed事件
timer.Enabled = true;
//绑定Elapsed事件
timer.Elapsed += new System.Timers.ElapsedEventHandler(TimeOut);
timer.Start();
}
}
}
catch (SocketException ex)
{
Console.WriteLine($"Message = {ex.Message} Error code = {ex.ErrorCode}");
TryToConnet(name, port);
}
}
//连接完成将缓冲区的数据发送到服务器
private void TimeOut(object sender, ElapsedEventArgs e)
{
if (stringList.Count > 0)
{
SendMsg(stringList[0]);
}
else
{
timer.Stop();
}
}
public void Close()
{
if (tcpClient != null && tcpClient.Connected)
{
tcpClient.Close();
}
}
//判断连接断开
bool IsConnected()
{
bool isConnected = true;
try
{
// Detect if client disconnected
if (tcpClient != null && tcpClient.Poll(0, SelectMode.SelectRead))
{
byte[] buff = new byte[1];
if (tcpClient.Receive(buff, SocketFlags.Peek) == 0)
{
// Client disconnected
isConnected = false;
}
}
}
catch (SocketException se)
{
Console.WriteLine($" se.ErrorCode == {se.ErrorCode} se.Message == {se.Message}");
isConnected = false;
}
return isConnected;
}
//发送消息和重连
public void SendMsg(string msg)
{
if (!stringList.Contains(msg))
{
stringList.Add(msg);
}
if (null == tcpClient || !tcpClient.Connected)
{
return;
}
try
{
if (IsConnected())
{
byte[] msgBytes = Encoding.UTF8.GetBytes(stringList[0]);
tcpClient.Send(msgBytes);
stringList.RemoveAt(0);
}
else
{
TryToConnet(name, port);
}
}
catch (SocketException e)
{
Console.WriteLine("{0} Error code: {1}.", e.Message, e.ErrorCode);
}
catch (ObjectDisposedException obj)
{
Console.WriteLine(string.Format("ObjectDisposedException:{0}", obj.Message));
}
}
}
}
|