vb networking problem


B

Ben

I modified the logmonitor sdk example so it would work over a network. It
works great when the client and server are running on the same PC and have
administrator privileges. So I have two problems:
1) I cannot run the client without administrator privileges. If I try I get
the following message:
Unhandled Exception: System.Security.SecurityException: Requested registry
access is not allowed.
at System.ThrowHelper.ThrowSecurityException(ExceptionResource resource)
at Microsoft.Win32.RegistryKey.OpenSubKey(String name, Boolean writable)
at System.Diagnostics.EventLog.Exists(String logName, String machineName)
at LogMonitor_Client.Microsoft.Samples.LogMonitor.Main()
The Zone of the assembly that failed was:
MyComputer
I have a try catch in the client so I don't know what the problem is. What
am I doing wrong?

2) My server crashes when a remote client disconnects. Here is its message:
Unhandled Exception: System.Net.Sockets.SocketException: An existing
connection was forcibly closed by the remote host
at System.Net.Sockets.Socket.BeginReceive(Byte[] buffer, Int32 offset,
Int32size, SocketFlags socketFlags, syncCallback callback, Object state)
at LogMonitor_Server.Module1.AcceptCallback(IAsyncResult ar)
at System.Net.LazyAsyncResult.Complete(IntPtr userToken)
at System.Net.ContextAwareResult.CaptureOrComplete(ExecutionContext&
cachedContext, Boolean returnContext)
at System.Net.ContextAwareResult.FinishPostingAsyncOp(CallbackClosure&
closure)
at System.Net.Sockets.Socket.BeginAccept(AsyncCallback callback, Object
state)
at LogMonitor_Server.Module1.Main()

I don't know why the server always crashes when a remote client leaves. If
I run the client and server on the same machine and have the client leave
the server stays running. What am I doing wrong?

Thanks,

Here is the client:
Public Class StateObject
Public workSocket As System.Net.Sockets.Socket = Nothing
Public Const BufferSize As Integer = 256
Public buffer(BufferSize) As Byte
Public sb As New System.Text.StringBuilder
End Class

Namespace Microsoft.Samples
Module LogMonitor
Dim WithEvents evtApp As New EventLog("Application")
Dim WithEvents evtSys As New EventLog("System")
Dim WithEvents evtSec As New EventLog("Security")

Private connectDone As New System.Threading.ManualResetEvent(False)
Private sendDone As New System.Threading.ManualResetEvent(False)
Private receiveDone As New System.Threading.ManualResetEvent(False)
Private response As String = String.Empty

Public Sub Main()
If (Not EventLog.Exists("system", ".")) Then
MsgBox("The sytem log does not exist!", , "Error")
Exit Sub
End If
If (Not EventLog.Exists("application", ".")) Then
MsgBox("The application log does not exist!", , "Error")
Exit Sub
End If
If (Not EventLog.Exists("security", ".")) Then
MsgBox("The security log does not exist!", , "Error")
Exit Sub
End If

evtApp.MachineName = System.Net.Dns.GetHostName
evtSys.MachineName = System.Net.Dns.GetHostName
evtSec.MachineName = System.Net.Dns.GetHostName
AddHandler evtApp.EntryWritten, AddressOf OnEntryWritten
evtApp.EnableRaisingEvents = True
AddHandler evtSys.EntryWritten, AddressOf OnEntryWritten
evtSys.EnableRaisingEvents = True
AddHandler evtSec.EntryWritten, AddressOf OnEntryWritten
evtSec.EnableRaisingEvents = True

While (Console.Read() <> 113)
System.Threading.Thread.Sleep(14500)
End While
End Sub

Sub OnEntryWritten(ByVal source As Object, ByVal e As EntryWrittenEventArgs)
Handles evtApp.EntryWritten, evtSec.EntryWritten, evtSys.EntryWritten
Dim checkinfo As String
Dim checkwarn As String
Dim checkerror As String
Dim checksucc As String
Dim checkfail As String
Dim checkserver As String
Dim checkport As String
Try
checkinfo =
My.Computer.Registry.GetValue("HKEY_LOCAL_MACHINE\Software\Dravet", "info",
Nothing)
checkwarn =
My.Computer.Registry.GetValue("HKEY_LOCAL_MACHINE\Software\Dravet", "warn",
Nothing)
checkerror =
My.Computer.Registry.GetValue("HKEY_LOCAL_MACHINE\Software\Dravet", "error",
Nothing)
checksucc =
My.Computer.Registry.GetValue("HKEY_LOCAL_MACHINE\Software\Dravet", "succ",
Nothing)
checkfail =
My.Computer.Registry.GetValue("HKEY_LOCAL_MACHINE\Software\Dravet", "fail",
Nothing)
checkserver =
My.Computer.Registry.GetValue("HKEY_LOCAL_MACHINE\Software\Dravet",
"server", Nothing)
checkport =
My.Computer.Registry.GetValue("HKEY_LOCAL_MACHINE\Software\Dravet",
"portnum", Nothing)
If (checkinfo.ToUpper = "TRUE") And (e.Entry.EntryType =
EventLogEntryType.Information) Then
sendinfo(e, checkserver, checkport)
Exit Sub
End If
If (checkwarn.ToUpper = "TRUE") And (e.Entry.EntryType =
EventLogEntryType.Warning) Then
sendinfo(e, checkserver, checkport)
Exit Sub
End If
If (checkerror.ToUpper = "TRUE") And (e.Entry.EntryType =
EventLogEntryType.Error) Then
sendinfo(e, checkserver, checkport)
Exit Sub
End If
If (checksucc.ToUpper = "TRUE") And (e.Entry.EntryType =
EventLogEntryType.SuccessAudit) Then
sendinfo(e, checkserver, checkport)
Exit Sub
End If
If (checkfail.ToUpper = "TRUE") And (e.Entry.EntryType =
EventLogEntryType.FailureAudit) Then
sendinfo(e, checkserver, checkport)
Exit Sub
End If

Catch se As System.Security.SecurityException
Catch se2 As System.UnauthorizedAccessException
MsgBox("A Security Exception has occurred", , "LogMonitor Error")
End Try
End Sub

Sub sendinfo(ByVal e As EntryWrittenEventArgs, ByVal servername As String,
ByVal portnum As String)
Dim sendbuffer As String
Dim ipHostInfo As System.Net.IPHostEntry =
System.Net.Dns.GetHostEntry(servername)
Dim ipAddress As System.Net.IPAddress = ipHostInfo.AddressList(0)
Dim remoteEP As New System.Net.IPEndPoint(ipAddress, portnum)
Dim client As New
System.Net.Sockets.Socket(System.Net.Sockets.AddressFamily.InterNetwork,
System.Net.Sockets.SocketType.Stream, System.Net.Sockets.ProtocolType.Tcp)
Dim hostname As String = System.Net.Dns.GetHostName()
client.BeginConnect(remoteEP, New AsyncCallback(AddressOf ConnectCallback),
client)
connectDone.WaitOne()
sendbuffer = hostname & "<BREAK>" & e.Entry.Message & "<EOF>"
Send(client, sendbuffer)
sendDone.WaitOne()
client.Shutdown(System.Net.Sockets.SocketShutdown.Both)
client.Close()
End Sub

Private Sub ConnectCallback(ByVal ar As IAsyncResult)
Dim client As System.Net.Sockets.Socket = CType(ar.AsyncState,
System.Net.Sockets.Socket)
client.EndConnect(ar)
connectDone.Set()
End Sub

Private Sub Receive(ByVal client As System.Net.Sockets.Socket)
Dim state As New StateObject
state.workSocket = client
client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, New
AsyncCallback(AddressOf ReceiveCallback), state)
End Sub

Private Sub ReceiveCallback(ByVal ar As IAsyncResult)
Dim state As StateObject = CType(ar.AsyncState, StateObject)
Dim client As System.Net.Sockets.Socket = state.workSocket
Dim bytesRead As Integer = client.EndReceive(ar)
If bytesRead > 0 Then
' There might be more data, so store the data received so far.
state.sb.Append(System.Text.Encoding.ASCII.GetString(state.buffer, 0,
bytesRead))
' Get the rest of the data.
client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, New
AsyncCallback(AddressOf ReceiveCallback), state)
Else
' All the data has arrived; put it in response.
If state.sb.Length > 1 Then
response = state.sb.ToString()
End If
receiveDone.Set()
End If
End Sub

Private Sub Send(ByVal client As System.Net.Sockets.Socket, ByVal data As
String)
Dim byteData As Byte() = System.Text.Encoding.ASCII.GetBytes(data)
client.BeginSend(byteData, 0, byteData.Length, 0, New
AsyncCallback(AddressOf SendCallback), client)
End Sub

Private Sub SendCallback(ByVal ar As IAsyncResult)
Dim client As System.Net.Sockets.Socket = CType(ar.AsyncState,
System.Net.Sockets.Socket)
Dim bytesSent As Integer = client.EndSend(ar)
sendDone.Set()
End Sub
End Module
End Namespace

SERVER ----------------------------------------------------------------------------
Public Class StateObject
Public workSocket As System.Net.Sockets.Socket = Nothing
Public Const BufferSize As Integer = 1024
Public buffer(BufferSize) As Byte
Public sb As New System.Text.StringBuilder
End Class

Module Module1
Dim portnum As String
Dim SBuffer(4096) As Byte
Dim SBytes As Integer
Public allDone As New System.Threading.ManualResetEvent(False)

Sub Main()
Dim args As String()
args = Environment.GetCommandLineArgs()
portnum = args(1)
If Not IsNumeric(portnum) Then
Console.WriteLine("Usage: LogMonitor.exe portnumber")
Console.WriteLine()
Console.WriteLine("Press Enter to continue...")
Console.ReadLine()
Exit Sub
End If
If (args.Length <> 2) Then
Console.WriteLine("Usage: LogMonitor.exe portnumber")
Console.WriteLine()
Console.WriteLine("Press Enter to continue...")
Console.ReadLine()
Exit Sub
End If

Dim theIPEndPoint As System.Net.IPEndPoint = New
System.Net.IPEndPoint(System.Net.IPAddress.Any, portnum)
Dim ServerSocket As System.Net.Sockets.Socket = New
System.Net.Sockets.Socket(Net.Sockets.AddressFamily.InterNetwork,
Net.Sockets.SocketType.Stream, Net.Sockets.ProtocolType.Tcp)
ServerSocket.Blocking = True
ServerSocket.Bind(theIPEndPoint)
ServerSocket.Listen(10)
While True
allDone.Reset()
Console.WriteLine("Waiting for a connection...")
ServerSocket.BeginAccept(New AsyncCallback(AddressOf
AcceptCallback), ServerSocket)
allDone.WaitOne()
End While
End Sub

Public Sub AcceptCallback(ByVal ar As IAsyncResult)
Dim listener As System.Net.Sockets.Socket = CType(ar.AsyncState,
System.Net.Sockets.Socket)
Dim handler As System.Net.Sockets.Socket = listener.EndAccept(ar)
Dim state As New StateObject
state.workSocket = handler
handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, New
AsyncCallback(AddressOf ReadCallback), state)
End Sub

Public Sub ReadCallback(ByVal ar As IAsyncResult)
Dim content As String = String.Empty
Dim state As StateObject = CType(ar.AsyncState, StateObject)
Dim handler As System.Net.Sockets.Socket = state.workSocket
Dim bytesRead As Integer = handler.EndReceive(ar)
Dim dotposition As Integer
Dim buffer As String
Dim hostname As String
If bytesRead > 0 Then
' There might be more data, so store the data received so far.
state.sb.Append(System.Text.Encoding.ASCII.GetString(state.buffer,
0, bytesRead))
' Check for end-of-file tag. If it is not there, read more data.
content = state.sb.ToString()
If content.IndexOf("<EOF>") > -1 Then
' All the data has been read from the client. Display it on the
console.
dotposition = InStr(content, "<BREAK>") - 1
hostname = Left(content, dotposition)
buffer = Replace(content, "<EOF>", "")
buffer = Right(buffer, buffer.Length - hostname.Length - 7)
MsgBox(buffer, , "Eventlog Alert from " & hostname)
' Echo the data back to the client.
Send(handler, content)
Else
' Not all data received. Get more.
handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
New AsyncCallback(AddressOf ReadCallback), state)
End If
End If
End Sub

Private Sub Send(ByVal handler As System.Net.Sockets.Socket, ByVal data As
String)
Dim byteData As Byte() = System.Text.Encoding.ASCII.GetBytes(data)
handler.BeginSend(byteData, 0, byteData.Length, 0, New
AsyncCallback(AddressOf SendCallback), handler)
End Sub

Private Sub SendCallback(ByVal ar As IAsyncResult)
Dim handler As System.Net.Sockets.Socket = CType(ar.AsyncState,
System.Net.Sockets.Socket)
Dim bytesSent As Integer = handler.EndSend(ar)
Console.WriteLine("Sent {0} bytes to client.", bytesSent)
handler.Shutdown(System.Net.Sockets.SocketShutdown.Both)
handler.Close()
allDone.Set()
End Sub
End Module
 
Ad

Advertisements


Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top