,PC以太网与PLC通讯,当连接PLC的网线断开后,电脑在联网时能立刻try到Socket的Send与Recieve的超时错误,电脑在没有联网的状态线下要20s左右能try到错误,为什么?有没有大佬能解答一下?
可以ping 通,我就是在调试,在拔掉PLC与电脑连接网线之时,为什么电脑联网与不联网两种情况捕捉异常的时间会差很多
IPAddress address = IPAddress.Parse(AddressIp); // 创建包含ip和端口号的网络节点对象;
IPEndPoint endPoint = new IPEndPoint(address, int.Parse(EndPt));//PLC端口号的网络节点对象
IPEndPoint endPoint1 = new IPEndPoint(ipa, LocalPort);//本地
sockClientIp[i].SendTimeout = 500;
sockClientIp[i].ReceiveTimeout = 1000;
try
{
sockClientIp[i].Bind(endPoint1);
connResult = sockClientIp[i].BeginConnect(endPoint,null,null );
connResult.AsyncWaitHandle.WaitOne(2000, true);
Thread.Sleep(100);
if (connResult.IsCompleted != false && sockClientIp[i].Connected == true)
{
MessageList.Add(IPList[nums] + ">>>>>链接成功>>>>>");
index = 1;
StrSplit(StrIpa, ref LocalNetworkAdress);
StrSplit(AddressIp, ref LNetworkAdress);
}
else
{
//sockClientIp[i].Close();
MessageList.Add(IPList[nums] + ">>>>链接失败>>>>");
index = 0;
}
}
catch (SocketException se)
{
sockClientIp[i].Close();
MessageList.Add(IPList[nums] + ">>链接失败>>>>>" + se.Message);
index = 0;
break;
}
可以考虑先ping一下来测试是否连通。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using System.Net;
using System.Net.Sockets;
namespace CoreStudio.TCPCommunication
{
/// <summary>
/// 连接服务器
/// </summary>
public class TimeOutSocket
{
private bool IsConnectionSuccessful = false;
private Exception socketexception;
private ManualResetEvent TimeoutObject = new ManualResetEvent(false);
/// <summary>
/// 开启异步连接操作,并设置指定超时时间
/// </summary>
/// <param name="remoteEndPoint"></param>
/// <param name="timeoutMiliSecond"></param>
/// <returns></returns>
public TcpClient TryConnect(IPEndPoint remoteEndPoint, int timeoutMiliSecond)
{
TimeoutObject.Reset();
socketexception = null;
string serverip = Convert.ToString(remoteEndPoint.Address);
int serverport = remoteEndPoint.Port;
TcpClient tcpclient = new TcpClient();
tcpclient.BeginConnect(serverip, serverport,
new AsyncCallback(CallBackMethod), tcpclient);
if (TimeoutObject.WaitOne(timeoutMiliSecond, false))
{
if (IsConnectionSuccessful)
{
return tcpclient;
}
else
{
throw socketexception;
}
}
else
{
tcpclient.Close();
throw new TimeoutException("TimeOut Exception");
}
}
/// <summary>
/// 连接
/// </summary>
/// <param name="asyncresult"></param>
private void CallBackMethod(IAsyncResult asyncresult)
{
try
{
IsConnectionSuccessful = false;
TcpClient tcpclient = asyncresult.AsyncState as TcpClient;
if (tcpclient.Client != null)
{
tcpclient.EndConnect(asyncresult);
IsConnectionSuccessful = true;
}
}
catch (Exception ex)
{
IsConnectionSuccessful = false;
socketexception = ex;
}
finally
{
TimeoutObject.Set();
}
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace CoreStudio.TCPCommunication
{
public class SocketConnect
{
private string m_IP = "127.0.0.1";
public delegate void MsgHandler(Byte[] v);
public event MsgHandler m_MSGMessage;
private Socket m_Socket;
/// <summary>
/// 连接IP
/// </summary>
public string IP
{
get { return m_IP; }
set { m_IP = value; }
}
private int m_Port = 502;
/// <summary>
/// 连接端口
/// </summary>
public int Port
{
get { return m_Port; }
set { m_Port = value; }
}
private TimeOutSocket timeout = new TimeOutSocket();
/// <summary>
/// 通讯线程开关
/// </summary>
public bool Starts = false;
private Byte[] m_Message;
/// <summary>
/// 接收到的主控系统指令
/// </summary>
public Byte[] Message
{
get { return m_Message; }
set
{
m_Message = value;
OnChange(m_MSGMessage, m_Message);
m_Message = null;
}
}
private void OnChange(MsgHandler hand, Byte[] v)
{
if (hand != null)
{
hand(v);
}
}
public SocketConnect(string IP, int Port)
{
this.IP = IP;
this.Port = Port;
}
/// <summary>
/// 开启通讯
/// </summary>
/// <returns></returns>
public bool Connect(int Time)
{
try
{
IPAddress ip = IPAddress.Parse(IP);
IPEndPoint Point = new IPEndPoint(ip, Convert.ToInt32(Port));
TcpClient cp = new TcpClient();
m_Socket = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
try
{
cp = timeout.TryConnect(Point, Time);
}
catch (Exception)
{
}
if (cp.Connected)
{
Console.WriteLine("a");
m_Socket = cp.Client;
Starts = true;
Thread thread = new Thread(Receive);
thread.IsBackground = true;
thread.Start();
return true;
}
else
{
Starts = false;
return false;
}
}
catch (Exception)
{
Starts = false;
return false;
}
}
private object o = new object();
/// <summary>
/// 监控主控系统发送的消息
/// </summary>
private void Receive()
{
while (Starts)
{
lock (o)
{
try
{
byte[] buffer = new byte[1024 * 1024 * 3];
int len = m_Socket.Receive(buffer);
if (len == 0)
{
continue;
}
Message = buffer;
Thread.Sleep(1);
}
catch (Exception ex)
{
}
}
}
}
/// <summary>
/// 断开通讯连接
/// </summary>
public void Disconnect(bool Reuse)
{
try
{
//m_Socket.Shutdown(SocketShutdown.Both);
m_Socket.Close();
//m_Socket.Disconnect(Reuse);
}
catch (Exception)
{
}
Starts = false;
}
/// <summary>
/// 判断连接状态
/// </summary>
/// <returns></returns>
public bool Chonglian()
{
try
{
if (!m_Socket.Connected)
{
try
{
Byte[] buffer = new byte[] { };
m_Socket.Send(buffer);
return true;
}
catch (ArgumentNullException)
{
return true;
}
catch (Exception)
{
return false;
}
}
return true;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
/// <summary>
/// 向主控系统发送数据
/// </summary>
/// <param name="data">要发送的数据</param>
public void SeedMessage(Byte[] data)
{
try
{
if (Starts)
{
m_Socket.Send(data);
//data = null;
//GC.Collect();
Thread.Sleep(100);
}
}
catch (System.Net.Sockets.SocketException es)
{
//if (Connect())
//{
// SeedMessage(data);
//}
//else
//{
// throw new Exception("发送数据失败,请检查连接!" + es.Message);
//}
throw new Exception("发送数据失败,请检查连接!" + es.Message);
}
catch (Exception ex)
{
throw new Exception("发送数据失败,请检查连接!" + ex.Message);
}
}
}
}
这是我简单设计的一种TCP通讯连接方式,可以设置启动连接时的超时时间,超过指定时间主动抛出异常,虽然不是很好,但我举得你可以参考参考