Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Socket Question - allDone.Set()

Status
Not open for further replies.

joejack0330

Technical User
Jan 27, 2006
95
0
0
US
We are using the standard example of vb socket program that's out on the web and works for the most part but lately, it hangs every once in awhile.

Some examples I see have the allDone.Set() in the AcceptCallBack function and some don't. Can anyone tell me exactly what that statement does and if should be there or not?

I am attaching our code.


Imports System
Imports System.Net
Imports System.Net.Sockets
Imports System.Text
Imports System.Threading
Imports System.Data.SqlClient
Imports Microsoft.VisualBasic
Imports System.IO

' State object for reading client data asynchronously

Public Class StateObject
' Client socket.
Public workSocket As Socket = Nothing
' Size of receive buffer.
Public Const BufferSize As Integer = 1024
' Receive buffer.
Public buffer(BufferSize) As Byte
' Received data string.
Public sb As New StringBuilder
End Class 'StateObject


Public Class AsynchronousSocketListener
' Thread signal.
Public Shared allDone As New ManualResetEvent(False)

' This server waits for a connection and then uses asychronous operations to
' accept the connection, get data from the connected client,
' echo that data back to the connected client.
' It then disconnects from the client and waits for another client.
Public Shared Sub Main()
' Data buffer for incoming data.
Dim bytes() As Byte = New [Byte](1023) {}

' Establish the local endpoint for the socket.
Dim ipHostInfo As IPHostEntry = Dns.GetHostEntry("VoiceServer1")
Dim ipAddress As IPAddress = ipHostInfo.AddressList(0)
Dim localEndPoint As New IPEndPoint(ipAddress, 20041)

' Create a TCP/IP socket.
Dim listener As New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)

' Bind the socket to the local endpoint and listen for incoming connections.
Try 'JJ - Added Try and Catch - 2/12/10
listener.Bind(localEndPoint)
listener.Listen(120) 'JJ - Changed from 100 - 2/10/10

' Added the following 2 lines on 2/2/10 to see if helps with socket hanging. - JJ
listener.ReceiveTimeout() = 5000
listener.SendTimeout() = 5000

Console.WriteLine()
Console.WriteLine("Version 1.11 Waiting for a connection...")
Console.WriteLine()

While True
' Set the event to nonsignaled state.
allDone.Reset()
' Start an asynchronous socket to listen for connections.
listener.BeginAccept(New AsyncCallback(AddressOf AcceptCallback), listener)
' Wait until a connection is made and processed before continuing.
allDone.WaitOne()
End While
Catch e As Exception
Console.WriteLine(e.ToString())
End Try

End Sub 'Main


Public Shared Sub AcceptCallback(ByVal ar As IAsyncResult)
allDone.Set() 'JJ - Added 2/10/10
' Get the socket that handles the client request.
Dim listener As Socket = CType(ar.AsyncState, Socket)
' End the operation.
Dim handler As Socket = listener.EndAccept(ar)
' Create the state object for the async receive.
Dim state As New StateObject
state.workSocket = handler
handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, New AsyncCallback(AddressOf ReadCallback), state)
End Sub 'AcceptCallback


Public Shared Sub ReadCallback(ByVal ar As IAsyncResult)
'On Error GoTo Err
Try
Dim content As String = String.Empty
' Retrieve the state object and the handler socket
' from the asynchronous state object.
Dim state As StateObject = CType(ar.AsyncState, StateObject)
Dim handler As Socket = state.workSocket
' Read data from the client socket.
Dim bytesRead As Integer = handler.EndReceive(ar)
If bytesRead > 0 Then 'jj? (close if no bytes?)
' There might be more data, so store the data received so far.
state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead))
Dim tempstring As String = (Encoding.ASCII.GetString(state.buffer, 0, bytesRead))
Dim AllSQLData As String
AllSQLData = String.Empty
content = state.sb.ToString()
If content.IndexOf(")") - 1 Then
Dim strindex As Integer = (content.IndexOf(")")) '- 1
Dim str1 As String = content
Dim str2 As Integer = str1.IndexOf("(")
Dim str3 As String = (content.Remove(strindex, content.Length - strindex))
str3 = Replace(str3, "(", " ")
str3 = Replace(str3, ")", "")
Dim conn As New SqlConnection("Initial Catalog=Production1;Data Source=172.16.1.183;Integrated Security=True; Connect Timeout=20")
conn.Open()

Dim myCommand As New SqlCommand(str3, conn)
Dim myReader As SqlDataReader = myCommand.ExecuteReader()
Dim numberOfFields As Integer = myReader.FieldCount
Dim i As Integer
Dim myRow As String

myReader.Read()
Dim fNextResult As Boolean = True
Do While fNextResult = True
myRow = String.Empty
For i = 0 To numberOfFields - 1
myRow = myRow & myReader.GetValue(i) & ","
Next
myRow = myRow & vbCrLf
AllSQLData = AllSQLData & myRow
fNextResult = myReader.Read()
Loop
AllSQLData = AllSQLData & vbCr & vbCr
myReader.Close()
conn.Close()
Send(handler, AllSQLData)
Else
'Not all data received. Get more. '''''''
handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, New AsyncCallback(AddressOf ReadCallback), state)
End If

Dim Device As String
Dim StartPosition As Integer
Dim EndPosition As Integer

Device = tempstring

StartPosition = InStr(Device, ",")
Device = Device.Substring(StartPosition)
StartPosition = InStr(Device, "'")
Device = Device.Substring(StartPosition)
EndPosition = InStr(Device, "'") - 1
Device = Device.Substring(0, EndPosition)

'Dim filename As String = Today()
'filename = filename.Replace("/", "_")
'Dim path As String = "c:\ServerLog\" + Device + "_" + filename + ".txt"
'Dim VoiceLog As System.IO.StreamWriter
'If Not File.Exists(path) Then
' VoiceLog = File.CreateText(path)
' VoiceLog.Close()
'End If
Console.WriteLine("Version 1.11 LOG TIME: " & Now() & " -Client " & Device & " Sent {0} bytes to server:", bytesRead)
'VoiceLog = New StreamWriter(path, True)
'VoiceLog.WriteLine("Version 1.11 START OF SESSION: " & " -LOG TIME: " & Now())
'VoiceLog.WriteLine("---- REQUEST FROM CLIENT TO SERVER ----")
'VoiceLog.WriteLine(tempstring & "---- RESPONSE FROM SERVER TO CLIENT ----")
'VoiceLog.WriteLine(AllSQLData & " - END OF SESSION BYTE")
'VoiceLog.WriteLine()
'VoiceLog.WriteLine()
'VoiceLog.WriteLine()
'VoiceLog.Close()
End If
Catch exception As System.Exception
Dim filename As String = Today()
filename = filename.Replace("/", "_")
Dim path As String = "c:\serverlog\" + "VoiceLogErrors_" + filename + ".txt"
Dim VoiceLogErrors As System.IO.StreamWriter
If Not File.Exists(path) Then
VoiceLogErrors = File.CreateText(path)
VoiceLogErrors.Close()
End If
VoiceLogErrors = New StreamWriter(path, True)
VoiceLogErrors.WriteLine("*******************************************************************************")
VoiceLogErrors.WriteLine("*******************************************************************************")
VoiceLogErrors.WriteLine("ERROR: ReadCallback: -LOG TIME: " & Now())
VoiceLogErrors.WriteLine(exception)
VoiceLogErrors.WriteLine("*******************************************************************************")
VoiceLogErrors.WriteLine("*******************************************************************************")
VoiceLogErrors.WriteLine()
VoiceLogErrors.Close()

Console.WriteLine("*******************************************************************************")
Console.WriteLine("*******************************************************************************")
Console.WriteLine("ERROR: ReadCallback: -LOG TIME: " & Now())
Console.WriteLine(exception)
Console.WriteLine("*******************************************************************************")
Console.WriteLine("*******************************************************************************")
Console.WriteLine()
Console.WriteLine("Version 1.11 Waiting for a connection...")
Console.WriteLine()
allDone.Set()
End Try
End Sub 'ReadCallback

Private Shared Sub Send(ByVal handler As Socket, ByVal data As String)
' Convert the string data to byte data using ASCII encoding.
Dim byteData As Byte() = Encoding.ASCII.GetBytes(data)
' Begin sending the data to the remote device.
handler.BeginSend(byteData, 0, byteData.Length, 0, New AsyncCallback(AddressOf SendCallback), handler)
End Sub 'Send

Private Shared Sub SendCallback(ByVal ar As IAsyncResult)
' Retrieve the socket from the state object.
Try
Dim handler As Socket = CType(ar.AsyncState, Socket)
' Complete sending the data to the remote device.
Dim bytesSent As Integer = handler.EndSend(ar)
Console.WriteLine("Version 1.11 LOG TIME: " & Now() & " -Server Sent {0} bytes to server: ", bytesSent)
handler.Shutdown(SocketShutdown.Both)
handler.Close()
' Signal the main thread to continue.
allDone.Set()
Catch exception As System.Exception
Dim filename As String = Today()
filename = filename.Replace("/", "_")
Dim path As String = "c:\serverlog\" + "VoiceLogErrors_" + filename + ".txt"
Dim VoiceLogErrors As System.IO.StreamWriter
If Not File.Exists(path) Then
VoiceLogErrors = File.CreateText(path)
VoiceLogErrors.Close()
End If
VoiceLogErrors = New StreamWriter(path, True)
VoiceLogErrors.WriteLine("*******************************************************************************")
VoiceLogErrors.WriteLine("*******************************************************************************")
VoiceLogErrors.WriteLine("ERROR: SendCallback: -LOG TIME: " & Now())
VoiceLogErrors.WriteLine(exception)
VoiceLogErrors.WriteLine("*******************************************************************************")
VoiceLogErrors.WriteLine("*******************************************************************************")
VoiceLogErrors.WriteLine()
VoiceLogErrors.Close()

Console.WriteLine("*******************************************************************************")
Console.WriteLine("*******************************************************************************")
Console.WriteLine("ERROR: SendCallback: -LOG TIME: " & Now())
Console.WriteLine(exception)
Console.WriteLine("*******************************************************************************")
Console.WriteLine("*******************************************************************************")
Console.WriteLine()
Console.WriteLine("Version 1.11 Waiting for a connection...")
Console.WriteLine()
allDone.Set() '''''''''Was always here but don't see in anohter example online so maybe remove??? JJ
End Try
End Sub 'SendCallback
End Class 'AsynchronousSocketListener



Thanks,
Joe
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top