![](/img/trans.png)
[英]C# Entity Framework Reconnecting to the database by new connection
[英]Reconnecting to an unclosed Socket connection C#
我有一个侦听器应用程序,希望显示一个字符串消息。 我无法修改此应用程序。 我必须通过我的C#客户端向该侦听器发送消息。 侦听器和客户端都应在同一台PC(本地主机)上运行。
我的连接代码:
public void ConnectAndSendMessage(string MessageToSend)
{
string localIP = GetIPAddress();
try
{
TcpClient tcpclnt = new TcpClient();
Console.WriteLine("Connecting.....");
tcpclnt.Connect(localIP, 2400);
Socket socket = tcpclnt.Client;
bool connectionStatus = socket.Connected;
if (connectionStatus)
{
//Send Message
ASCIIEncoding asen = new ASCIIEncoding();
//string sDateTime = DateTime.Now.ToString();
int SendStatus = socket.Send(asen.GetBytes(MessageToSend + Environment.NewLine));
}
Thread.Sleep(2000);
tcpclnt.Close();
}
catch (Exception e)
{
Console.WriteLine("Error..... " + e.StackTrace);
}
}
问题:
客户端应用程序可以正常运行,并将消息成功发送到侦听器。 但是问题出在执行tcpclnt.Close();
之前,如果客户端崩溃(我关闭了客户端程序tcpclnt.Close();
。 在这种情况下,如果我再次重新启动Client程序,则无法连接到套接字,因为应用程序在上次运行(崩溃运行)中没有关闭套接字。
在这种情况下如何重新连接到侦听器?
试试这个
public void ConnectAndSendMessage(string MessageToSend)
{
string localIP = GetIPAddress();
using (System.Net.Sockets.TcpClient tcpclnt = new System.Net.Sockets.TcpClient())
{
try
{
Console.WriteLine("Connecting.....");
tcpclnt.Connect(localIP, 2400);
using (System.Net.Sockets.Socket socket = tcpclnt.Client)
{
if (socket.Connected)
{
//Send Message
System.Text.ASCIIEncoding asen = new System.Text.ASCIIEncoding();
//string sDateTime = DateTime.Now.ToString();
int SendStatus = socket.Send(asen.GetBytes(MessageToSend + Environment.NewLine));
}
System.Threading.Thread.Sleep(2000);
}
}
catch (Exception e)
{
Console.WriteLine("Error..... " + e.StackTrace);
}
finally
{
if (tcpclnt != null && tcpclnt.Connected)
tcpclnt.Close();
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.