所以我的好老板给我带来了一个问题,因为我知道我在 C# 方面的方式(不是很好,但有点),并询问是否可以构建一个简单的 Syslog 服务器,而不是出去购买一个。所以我当然接受了挑战,然后去了城里。我开发了一个 Alpha 版本(它让应用程序将所有内容直接输入到数据库中),但他问我是否可以采用客户端与侦听器的方法(PIA 但合理)。现在我相信我已经正确构建了 TCPClient,但我被困在 TCPlistener 部分,如果有人能指出我正确的方向,我希望得到一些帮助。以下是我迄今为止编写的 3 个程序(alpha、客户端、以及部分侦听器)
Α:
EventLog alog = new EventLog();
alog.Log = "Application";
alog.MachineName = ".";
DateTime fifteenMinsAgo = DateTime.Now.AddMinutes(-15);
foreach (EventLogEntry entry in alog.Entries)
{
if (entry.TimeGenerated > fifteenMinsAgo)
{
SqlConnection sql = new SqlConnection("Server=x.x.x.x;Database=yy;User ID=abcd;password=efg");
sql.Open();
SqlCommand cmd = new SqlCommand(@"insert into ApplicationLog(Level,DateTime,Source,EventID,TaskCategory,ServerName,Message) values (@Level,@DateTime,@Source,@EventID,@TaskCategory,@ServerName,@Message)", sql);
cmd.Parameters.AddWithValue("@Level", entry.EntryType);
cmd.Parameters.AddWithValue("@DateTime", entry.TimeGenerated);
cmd.Parameters.AddWithValue("@Source", entry.Source);
cmd.Parameters.AddWithValue("@EventID", entry.InstanceId);
cmd.Parameters.AddWithValue("@TaskCategory", entry.Category);
cmd.Parameters.AddWithValue("@ServerName", entry.MachineName);
cmd.Parameters.AddWithValue("@Message", entry.Message);
cmd.ExecuteNonQuery();
sql.Close();
}
}
TCP客户端:
EventLog alog = new EventLog();
alog.Log = "Application";
alog.MachineName = ".";
DateTime fifteenMinsAgo = DateTime.Now.AddMinutes(-15);
foreach (EventLogEntry entry in alog.Entries)
{
if (entry.TimeGenerated > fifteenMinsAgo)
{
TcpClient client = new TcpClient();
IPEndPoint serverendpoint = new IPEndPoint(IPAddress.Parse("x.x.x.x"), yyyy);
client.Connect(serverendpoint);
NetworkStream clientstream = client.GetStream();
ASCIIEncoding encoder = new ASCIIEncoding();
byte[] buffer = encoder.GetBytes(entry.ToString());
clientstream.Write(buffer, 0, buffer.Length);
clientstream.Flush();
}
}
TCP监听器:
TcpListener tcpServerListener = new TcpListener(IPAddress.Parse("127.0.0.1"), yyyy);
tcpServerListener.Start();
Console.WriteLine("Server Started");
Socket serverSocket = tcpServerListener.AcceptSocket();
if (serverSocket.Connected)
{
NetworkStream serverSockStream = new NetworkStream(serverSocket);
serverSockStream.ReadByte();
}