如何在c#.net Windowsservice中记录端口活动?另外,以下代码是否有任何问题?插座编程对我来说是全新的。我什至无法登录。
public void Start()
{
try
{
// Read server IPAddress and port details from the config
string serverIP, serverPort;
serverIP = ConfigurationManager.AppSettings["ServerIP"];
serverPort = ConfigurationManager.AppSettings["ServerPort"];
// Initialize server IPAddress and port number
IPAddress serverIPAddress = IPAddress.Parse(serverIP);
int serverPortNumber = int.Parse(serverPort);
this.tcpListnr = new TcpListener(serverIPAddress, serverPortNumber);
this.tcpListnr.Start();
// Start listener thread
this.tcpListnrThread = new Thread(this.ThreadProc);
this.tcpListnrThread.Start();
}
catch (Exception ex)
{
if (Er != null)
this.Er.LogError(ex,"Error in Start ");
}
}
private void ThreadProc()
{
try
{
// Listen infinitly
while (true)
{
// Waiting for a connection
TcpClient tcpClient = this.tcpListnr.AcceptTcpClient();
// Connected
if (this.tcpListnrThread.IsAlive)
{
try
{
Thread readDataThread = new Thread(this.ReadDataThreadProc);// Read data in a separate thread
readDataThread.Start(tcpClient);
}
catch(Exception ex)
{
this.Er.LogError(ex,"Thread Abort");
}
}
}
}
catch (Exception ex)
{
if (Er != null)
this.Er.LogError(ex,"Error in ThreadProc - " );
}
}
这是一个示例。请注意,没有错误检查,没有检查流中还有更多数据等。但这可以帮助您开始。
// Bind ip and port
TcpListener listener = new TcpListener(new IPAddress(new byte[] { 127, 0, 0, 1 }), 12345);
// start listener
listener.Start();
// endless cycle
while (true)
{
// acept client
TcpClient client = listener.AcceptTcpClient();
// using bgworker instead of thread, i like it more :D
using (BackgroundWorker bw = new BackgroundWorker())
{
// sign for dowork
bw.DoWork += Bw_DoWork;
// run worker and passing TcpClient as argument
bw.RunWorkerAsync(client);
}
}
和数据过程部分
// this will execute every time in separate thread
// when listener accept connection
private static void Bw_DoWork(object sender, DoWorkEventArgs e)
{
TcpClient client = (TcpClient)e.Argument;
// set read buffer length
int inBuffLen = 1024;
// declare input buffer
byte[] inBuff = new byte[inBuffLen];
// we will use network stream to read
NetworkStream stream = client.GetStream();
// real data length
int rlen;
// read from stream 1024 bytes of data and
// in rlen we've got a REAL amount of data bytes
rlen = stream.Read(inBuff, 0, inBuffLen);
// declare data array
byte[] data = new byte[rlen];
// copy from source array to data array
Array.Copy(inBuff, data, rlen);
// now you can do with data whatever you want
var s = "";
for (int i = 0; i < data.Length; i++)
s += string.Format("{0:X2}", data[i]);
Debug.WriteLine(s);
}