C# 在tcp端口上侦听的Windows服务会定期减慢或停止接收数据。需要重新启动吗
我让windows服务在tcp端口上侦听。一切正常,但在该端口上发送数据的客户端无法连接到服务器。首先连接速度减慢,然后停止。NetStat不断显示端口上许多已建立的连接。我的tcp服务器代码是:C# 在tcp端口上侦听的Windows服务会定期减慢或停止接收数据。需要重新启动吗,c#,tcp,C#,Tcp,我让windows服务在tcp端口上侦听。一切正常,但在该端口上发送数据的客户端无法连接到服务器。首先连接速度减慢,然后停止。NetStat不断显示端口上许多已建立的连接。我的tcp服务器代码是: using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Diagnostics; using System.Linq; using Syst
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Net;
using System.Configuration;
using System.Net.Sockets;
using System.Data.SqlClient;
using System.Collections;
using System.Threading;
namespace GPRSWindowService
{
public partial class Service1 : ServiceBase
{
AppSettingsReader objAppSettingsReader = new AppSettingsReader();
DB_Interface DBC;
Hashtable siteDetails = new Hashtable();
public Service1()
{
InitializeComponent();
String ConnString = GetConnectionString();
DBC = new DB_Interface(ConnString);
}
int GetPort()
{
int port = int.Parse(Convert.ToString(objAppSettingsReader.GetValue("ServerPort", typeof(string))));
return port;
}
String GetIP()
{
String IP = Convert.ToString(objAppSettingsReader.GetValue("ServerIP", typeof(string)));
return IP;
}
String GetConnectionString()
{
string ServerIP = Convert.ToString(objAppSettingsReader.GetValue("strConnection", typeof(string)));
return ServerIP;
}
protected override void OnStart(string[] args)
{
ApplicationLog.Info("--service started---",this.GetType());
Start();
}
public void Start()
{
//NetAppLog_1.ErrorLog("--service started---");
ApplicationLog.Init();
ApplicationLog.Info("--service started---", this.GetType());
System.Threading.Thread thr = new System.Threading.Thread(GPRSReceiver);
thr.Start();
}
int GetSleep()
{
int sleep = Convert.ToInt32(objAppSettingsReader.GetValue("Sleep", typeof(string)));
return sleep;
}
public void GPRSReceiver()
{
while (true)
{
TcpListener server = null;
TcpClient client = null;
NetworkStream stream = null;
string Response = null;
try
{
// Set the TcpListener port.
Int32 port = GetPort();
ApplicationLog.Debug("--Port Number---" +port, this.GetType());
IPAddress localAddr = IPAddress.Parse(GetIP());
ApplicationLog.Debug("--IP Address---" +localAddr, this.GetType());
server = new TcpListener(localAddr, port);
// Start listening for client requests.
server.Start();
ApplicationLog.Debug("--LIistener start---", this.GetType());
Byte[] bytes;
String data = null;
// Enter the listening loop.
ApplicationLog.Debug("----Enter the listening loop.---", this.GetType());
while (true)
{
if (!server.Pending())
{
// NetAppLog.ErrorLog("----Sorry, no connection requests have arrived.---");
}
else
{
bytes = new Byte[600];
client = server.AcceptTcpClient();
ApplicationLog.Debug("----Tcp Client---" + client + "---" + DateTime.Now.ToString(), this.GetType());
bool clientStatus = client.Connected;
ApplicationLog.Debug("---Data Recieve start ---" + DateTime.Now + " :" + DateTime.Now.Millisecond.ToString() + "- clientStatus -" + clientStatus, this.GetType());
int NoOfTimes = 3;
for (int p = 0; p <= NoOfTimes; p++)
{
stream = client.GetStream();
if (stream.DataAvailable)
{
ApplicationLog.Debug("--In If Data is avaliable--- Time in second" + p + "---" + client + "---" + DateTime.Now.ToString(), this.GetType());
data = null;
int i;
i = stream.Read(bytes, 0, bytes.Length);
String DataReceivedAt = DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss") + "." + DateTime.Now.Millisecond.ToString();
// Translate data bytes to a ASCII string.
data = System.Text.Encoding.ASCII.GetString(bytes);
data = data.ToUpper();
ApplicationLog.Debug("------------Data Receive--------------" + DataReceivedAt + "Data :: " + data, this.GetType());
System.Threading.Thread thr2 = new System.Threading.Thread(delegate() { SaveGPRSDataToDB(data, DataReceivedAt); });
thr2.Start();
ApplicationLog.Debug("----Thread two started---", this.GetType());
//SaveGPRSDataToDB(data);
SqlParameter[] arrSqlParam1 = new SqlParameter[1];
arrSqlParam1[0] = new SqlParameter("@Msg", data);//usp_UpdateGPRSQuery
string Query1 = (string)DBC.ExecuteScalar("usp_GetUpdateGPRSCommand", arrSqlParam1, true);
//string Query1 = null;
ApplicationLog.Debug("----usp_GetUpdateGPRSCommand called---", this.GetType());
if ((Query1 != "False") && (Query1 != null))
{
Response = Query1;
}
else
{
Response = "*STRTU0!";
}
//}
byte[] msg = System.Text.Encoding.ASCII.GetBytes(Response);
stream.Write(msg, 0, msg.Length);
// Shutdown and end connection
ApplicationLog.Debug("---Ack Send & Data Recieve End ---" + client + "---" + DateTime.Now + " :" + DateTime.Now.Millisecond.ToString(), this.GetType());
string EOP = data.Substring((i - 1), 1);
if (EOP == ".")
{
NoOfTimes = 10;
}
else
{
stream.Flush();
stream.Close();
//client.Close();
break;
}
}
else
{
ApplicationLog.Debug("---Data is not avaliable in stream---", this.GetType());
//stream.Flush();
//stream.Close();
//client.Close();
int sleep_value = GetSleep();
//System.Threading.Thread.Sleep(1 * 1000);
System.Threading.Thread.Sleep(sleep_value);
}
}
if (client != null)
{
bool clientStatus2 = client.Connected;
ApplicationLog.Debug("--clientStatus2---" + clientStatus2,this.GetType());
if (clientStatus2)
{
ApplicationLog.Debug("------------client connected--------------", this.GetType());
stream.Flush();
stream.Close();
client.Close();
}
}
if (stream != null)
{
ApplicationLog.Debug("------------stream--------------" + stream.ToString(), this.GetType());
stream.Flush();
stream.Close();
}
}
}
}
catch (Exception e)
{
ApplicationLog.Exception("------------Exception in Connection--------------", e);
//server.Stop();
//client.Close();
}
finally
{
ApplicationLog.Debug("------------In Connection finally block--------------",this.GetType());
stream.Flush();
stream.Close();
client.Close();
server.Stop();
}
//NetAppLog.ErrorLog("--In outer while loop ---");
}
}
private void SaveGPRSDataToDB(string strMessage, string DataReceivedAt)
{
ApplicationLog.Debug("---Started SaveGPRSDataToDB ---" + DataReceivedAt,this.GetType());
SqlParameter[] arrSqlParam1 = new SqlParameter[2];
try
{
strMessage = strMessage.Replace("\0", "").Replace("\\R", "").Replace("\\N", "");
arrSqlParam1[0] = new SqlParameter("@Message", strMessage);
arrSqlParam1[1] = new SqlParameter("@ReceiveTime", DataReceivedAt);
//arrSqlParam1[1] = new SqlParameter("@ReceiveTime", DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss"));
int result = DBC.ExecuteNonQueryWithOutParameter("usp_AddGPRSRawData", arrSqlParam1, true);
ApplicationLog.Debug("---Ended SaveGPRSDataToDB ---" + DataReceivedAt + "Id In Table is :: " + result,this.GetType());
}
catch (Exception ex)
{
ApplicationLog.Exception("--------\n\n Exception in saving GPRS data at " + DataReceivedAt + "\n------------",ex);
}
finally
{
arrSqlParam1 = null;
}
}
public int getSiteDetails(string msg)
{
//Hashtable siteDetails = new Hashtable();
siteDetails.Add("12", "34343");
return 0;
}
protected override void OnStop()
{
//NetAppLog_1.ErrorLog("--service stoped---");
ApplicationLog.Info("--service stoped---",this.GetType());
}
}
}
使用系统;
使用System.Collections.Generic;
使用系统组件模型;
使用系统数据;
使用系统诊断;
使用System.Linq;
使用System.ServiceProcess;
使用系统文本;
Net系统;
使用系统配置;
使用System.Net.Sockets;
使用System.Data.SqlClient;
使用系统集合;
使用系统线程;
命名空间gprsWindowsService
{
公共部分类Service1:ServiceBase
{
AppSettingsReader objAppSettingsReader=新的AppSettingsReader();
DB_接口DBC;
Hashtable siteDetails=新的Hashtable();
公共服务1()
{
初始化组件();
String ConnString=GetConnectionString();
DBC=新的DB_接口(ConnString);
}
int GetPort()
{
int port=int.Parse(Convert.ToString(objAppSettingsReader.GetValue(“ServerPort”,typeof(string)));
返回端口;
}
字符串GetIP()
{
stringip=Convert.ToString(objAppSettingsReader.GetValue(“ServerIP”,typeof(String));
返回IP;
}
字符串GetConnectionString()
{
字符串ServerIP=Convert.ToString(objAppSettingsReader.GetValue(“strConnection”,typeof(string));
返回ServerIP;
}
启动时受保护的覆盖无效(字符串[]args)
{
ApplicationLog.Info(“--service started--”,this.GetType());
Start();
}
公开作废开始()
{
//NetAppLog_1.ErrorLog(“--service started--”);
ApplicationLog.Init();
ApplicationLog.Info(“--service started--”,this.GetType());
System.Threading.Thread thr=新的System.Threading.Thread(GPRSReceiver);
thr.Start();
}
int GetSleep()
{
int sleep=Convert.ToInt32(objAppSettingsReader.GetValue(“sleep”,typeof(string));
恢复睡眠;
}
公共无效GPRSReceiver()
{
while(true)
{
TcpListener服务器=null;
TcpClient client=null;
NetworkStream=null;
字符串响应=null;
尝试
{
//设置TcpListener端口。
Int32端口=GetPort();
ApplicationLog.Debug(“--端口号----”+端口,this.GetType());
IPAddress localAddr=IPAddress.Parse(GetIP());
ApplicationLog.Debug(“--IP地址--”+localAddr,this.GetType());
服务器=新的TcpListener(localAddr,端口);
//开始侦听客户端请求。
server.Start();
ApplicationLog.Debug(“--LIistener start--”,this.GetType());
字节[]字节;
字符串数据=null;
//进入监听循环。
ApplicationLog.Debug(----进入侦听循环。--”,this.GetType();
while(true)
{
如果(!server.Pending())
{
//NetAppLog.ErrorLog(“----抱歉,没有收到任何连接请求。--”;
}
其他的
{
字节=新字节[600];
client=server.AcceptTcpClient();
ApplicationLog.Debug(“----Tcp-Client----”+Client+“----”+DateTime.Now.ToString(),this.GetType());
bool clientStatus=client.Connected;
ApplicationLog.Debug(“--Data receive start--”+DateTime.Now+”:“+DateTime.Now.millis秒.ToString()+”-clientStatus-“+clientStatus,this.GetType());
中午时间=3;
对于(int p=0;p您对挂起和可用数据的使用是错误。研究原因,删除它们。此外,您没有使用i
,但您必须。修复所有这些问题,我将再次查看。此外,请将代码拆分为函数。这种方式很难理解。您如何处理这些问题?我甚至不知道循环的开始和结束位置。请紧急帮助
非常烦人。。。