我在ASP.net中有一个长时间运行的进程,它使用套接字来监听来自某些专有软件的数据。我有以下代码来读取端口13000上的数据。经过一段时间的不活动后,我得到一个异常,说明我无法访问已处置的对象。我知道这是因为套接字由于超时或代表我的编码不正确而关闭。它让我疯狂哈哈! 我基本上希望套接字保持打开直到我关闭它,所以我需要连接是健壮的。
你们中间有人能发现我遇到的一些问题。 简而言之,下面的代码建立了TCP / IP连接并读取数据。数据在进入时进行处理并存储在XML文件中。 函数“Update()”将生成的XML记录与CSV文件的记录进行比较,并生成输出XML文件。 但基本上它除了连接不断下降之外都有效。 提前感谢您的帮助!!!
{
System.Net.Sockets.TcpListener server = null;
try
{
// Set the TcpListener on port 13000.
Int32 port = 13000;
IPAddress localAddr = IPAddress.Any;
server = new System.Net.Sockets.TcpListener(localAddr, port);
// Start listening for client requests.
server.Start();
const int recsize = 39;
const int outputsize = 39;
// Buffer for reading data
Byte[] bytes = new Byte[4096];
String data = null;
while (true)
{
Console.Write("Waiting for a connection... ");
// Perform a blocking call to accept requests.
// You could also user server.AcceptSocket() here.
System.Net.Sockets.TcpClient client = server.AcceptTcpClient();
Console.WriteLine("Connected!");
data = null;
// Get a stream object for reading and writing
NetworkStream stream = client.GetStream();
int i;
int x = 0;
// Loop to receive all the data sent by the client.
while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
{/////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////
// Translate data bytes to a ASCII string.
data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
// data = System.Text.Encoding.UTF32.GetString(bytes,0,i);
// Process the data sent by the client.
data = data.ToUpper();
var Data_out1 = ("AnnouncerKit@AckPong@$");
var Data_out2 = ("AnnouncerKit@Ping@$");
var Data_out4 = ("AnnouncerKit@GetInfo@$");
byte[] msg = System.Text.Encoding.ASCII.GetBytes(data);
var Data_In = data.ToString().Split('@');
byte[] byteArray = System.Text.Encoding.ASCII.GetBytes(Data_out1);
byte[] buffer = System.Text.Encoding.UTF8.GetBytes(Data_out1);
byte[] buffer2 = System.Text.Encoding.UTF8.GetBytes(Data_out2);
byte[] buffer4 = System.Text.Encoding.UTF8.GetBytes(Data_out4);
var Data_out3 = ("AnnouncerKit@AckStore@" + Data_In[Data_In.Length - 2] + "@$");
byte[] buffer3 = System.Text.Encoding.UTF8.GetBytes(Data_out3);
if (Data_In[1] == "PONG")
{
stream.Write(buffer, 0, buffer.Length);
stream.Write(buffer2, 0, buffer2.Length);
}
if (Data_In[1] == "ACKPING")
{
stream.Write(buffer4, 0, buffer4.Length);
}
if (Data_In[1] == "STORE")
{
stream.Write(buffer3, 0, buffer3.Length);
Response.Write(Data_In[0]);
}
var date = DateTime.Now.ToString("ddMMyyyy");
// TextBox1.Text = date.ToString();
var save = Request.QueryString["Racename"].ToString() + "_" + date + ".xml";
// var save = "RaceData_" + date + ".xml";
// String SaveDirectory = Server.MapPath.SaveDirectory((save));
string directoryMyLaps = Server.MapPath("~/MYLAPS Files/");
Directory.SetCurrentDirectory(directoryMyLaps);
if (!File.Exists(save))
{
System.Xml.Linq.XDocument doc = new XDocument(new XElement("bodies"));
doc.Save(save); //save with todays date and event name
}
System.Xml.XmlDocument doc2 = new XmlDocument();
doc2.Load(save);
foreach (string s in data.Split('@'))
{
if (s.Length == recsize)
{
// Console.WriteLine(data);
// TextBox1.Text = data;
string racerdata = s.Substring(0, outputsize);
// XmlElement test = doc2.CreateElement("RaceData");
XmlElement fileElement = doc2.CreateElement("body");
XmlElement boxName = doc2.CreateElement("Device_Name");
XmlElement bibid = doc2.CreateElement("ChipCode");
XmlElement time = doc2.CreateElement("Time");
bibid.InnerText = racerdata.Substring(0, 7);
fileElement.AppendChild(bibid);
boxName.InnerText = Data_In[0];
fileElement.AppendChild(boxName);
time.InnerText = racerdata.Substring(7, 13);
fileElement.AppendChild(time);
//Here getting the root element
//Here appending the "File" element to the root element.
XmlElement rootElement = (XmlElement)doc2.SelectSingleNode("bodies");
rootElement.AppendChild(fileElement);
}
}
doc2.Save(save);
Update(); //function that compares the received XML data to a CSV
}
}
// Shutdown and end connection
client.Close();
// Update();
}
}
catch (SocketException ex)
{
// server.Stop();
Console.WriteLine("SocketException: {0}", ex);
}
finally
{
// Stop listening for new clients.
server.Stop();
}
}