主程序代码
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.ServiceProcess;
using System.Text;
using System.Net.Sockets;
using System.Net;
using System.Threading;
using System.IO;
namespace Net_Port_Listener
{
public partial class Net_Port_Listener : ServiceBase
{
private TcpListener listener;
private Thread thread;
private TcpClient client;
private NetworkStream nsStream;
private StreamReader srRead;
public Net_Port_Listener()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
thread = new Thread(new ThreadStart(this.Listeners));
thread.Start();
}
protected override void OnStop()
{
thread.Join();
listener.Stop();
thread.Abort();
}
private void Listeners()
{
IPAddress ip = GetServerIP();
listener = new TcpListener(ip, 8000);
listener.Start();
while (true)
{
try
{
client = listener.AcceptTcpClient();
thread = new Thread(new ThreadStart(this.mainServer));
thread.IsBackground = true;
thread.Start();
}
catch (System.Security.SecurityException)
{
Console.Write("Listen faild!");
}
finally
{
thread.Abort();
}
}
}
public IPAddress GetServerIP()
{
IPHostEntry ieh = Dns.GetHostByName(Dns.GetHostName());
return ieh.AddressList[0];
}
private void mainServer()
{
nsStream = client.GetStream();
srRead = new StreamReader(nsStream);
string data = srRead.ReadToEnd();
int start = data.IndexOf("<dev>");
int end = data.LastIndexOf("</dev>");
string name = data.Substring(start, end);
string path = "D:/Data Log/";
WriteFile(path,data,name);
}
public static void WriteFile(string Path, string Strings, string Name)
{
string time = System.DateTime.Now.ToShortDateString();
Path += time;
Path = Path + "/" + Name + ".txt";
if (!System.IO.File.Exists(Path))
{
System.IO.FileStream f = System.IO.File.Create(Path);
f.Close();
}
System.IO.StreamWriter f2 = new System.IO.StreamWriter(Path, true, System.Text.Encoding.GetEncoding(0));
f2.WriteLine(Strings);
f2.Close();
f2.Dispose();
}
}
}