我有一个Windows服务侦听tcp端口。一切顺利,但是在此端口上发送数据的客户端无法连接到服务器。首先连接减慢然后停止。 NetStat一直在端口上显示许多已建立的连接。我的tcp服务器代码是:
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());
}
}
}