I've written a server and a client application using asynchronous sockets.The client sends data packets for every 7 seconds.The server receives the packets.
This process proceeds smoothly without any errors but,sometimes I get the following error.
"An existing connection was forcibly closed by the remote host."
Why is this happening when i am not closing the client program?
Could someone guide me in this issue
I am sending the code.
SERVER
Expand|Select|Wrap|Line Numbers
- Imports System
- Imports System.Math
- Imports System.Text
- Imports System.Threading
- Imports System.Net
- Imports System.Net.Sockets
- Module Module1
- ' Global variables Section
- Dim str_Insert1, str_Insert2 As String
- Dim Sim_Veh_ID As Int64 = 0
- Dim str_select_simvehid As Int64 = 0
- Dim Str_Select_EmpID As String = ""
- Dim Str_Select_Mobile As String = ""
- Dim Dbl_Prev_Long, Dbl_Prev_Lat As Double
- Dim Dbl_Total_Dist As Double = 0
- Dim Str_Select_TripID As String
- Dim Dbl_Emp_Long, Dbl_Emp_Lat, Dbl_Emp_Dist As Double
- Sub Main()
- ' Try
- If Path() Then
- AsynchronousSocketListener.StartListening()
- End If
- ' Catch ex As Exception
- 'Console.WriteLine(ex.Message)
- 'Log("Error in Main Function " & ex.Message & Now)
- 'End Try
- End Sub
- Public Class StateObject
- Public workSocket As Socket = Nothing
- Public Const BufferSize As Integer = 200
- Public buffer(BufferSize) As Byte
- Public sb As New StringBuilder
- End Class
- Public Class AsynchronousSocketListener
- Public Shared data As String = Nothing
- Public Shared allDone As New ManualResetEvent(False)
- Shared str_Error As String
- Public Shared Sub StartListening()
- ' Try
- Dim bytes() As Byte = New [Byte](1024) {}
- Dim ipHostInfo As IPHostEntry = Dns.GetHostEntry(Dns.GetHostName())
- Dim ipAddress As IPAddress = ipHostInfo.AddressList(0)
- Dim localEndPoint As New IPEndPoint(ipAddress, str_Port)
- Dim listener As New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
- 'Try
- listener.Bind(localEndPoint)
- listener.Listen(1000)
- While True
- allDone.Reset()
- Console.WriteLine("Waiting for a connection... on Port No:")
- Console.WriteLine(localEndPoint)
- listener.BeginAccept(New AsyncCallback(AddressOf AcceptCallback), listener)
- allDone.WaitOne()
- End While
- ' Catch e As Exception
- 'Console.WriteLine(E.Message)
- 'Log("Error in Sample Form StartListening Second try " & E.Message & Now)
- '' End Try
- 'Console.WriteLine(ControlChars.Cr + "Press ENTER to continue...")
- 'Console.Read()
- '' Catch ex As Exception
- 'Console.WriteLine(ex.Message)
- 'Log("Error in Sample Form StartListening First Try " & ex.Message & Now)
- 'End Try
- End Sub
- Public Shared Sub AcceptCallback(ByVal ar As IAsyncResult)
- ' Try
- allDone.Set()
- Dim listener As Socket = CType(ar.AsyncState, Socket)
- Dim handler As Socket = listener.EndAccept(ar)
- Dim state As New StateObject
- state.workSocket = handler
- Console.WriteLine("Connection Established........")
- handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, New AsyncCallback(AddressOf ReadCallback), state)
- 'Catch ex As Exception
- ' Console.WriteLine(ex.Message)
- ' Log("Error in Sample Form Acceptcallback " & ex.Message & Now)
- 'End Try
- End Sub
- Public Shared Sub ReadCallback(ByVal ar As IAsyncResult)
- ' Try
- Dim state As StateObject = CType(ar.AsyncState, StateObject)
- Dim handler As Socket = state.workSocket
- Dim bytesRead As Integer
- bytesRead = state.sb.Capacity
- bytesRead = handler.EndReceive(ar)
- If bytesRead > 0 Then
- state.sb.Append(Encoding.Default.GetString(state.buffer, 0, bytesRead))
- state.sb.Replace(" ", "")
- state.sb.Replace(Chr(13), "")
- state.sb.Replace(vbCr, "")
- If InStr(state.sb.ToString, "<") > 0 And InStr(state.sb.ToString, ">") > 0 Then
- Dim str_MSG As String
- str_MSG = state.sb.ToString.Trim
- Console.WriteLine(str_MSG)
- Dim ch_tmp, TmpMsg As String
- str_MSG = Mid(str_MSG, InStr(str_MSG, "<"), InStr(str_MSG, ">"))
- ch_tmp = str_MSG
- TmpMsg = ""
- For i As Integer = 1 To Len(str_MSG)
- ch_tmp = ""
- ch_tmp = Mid(str_MSG, i, 1)
- If (Asc(ch_tmp) >= 65 And Asc(ch_tmp) <= 90) Or (Asc(ch_tmp) >= 97 And Asc(ch_tmp) <= 122) Or (Asc(ch_tmp) >= 48 And Asc(ch_tmp) <= 57) Or Asc(ch_tmp) = 60 Or Asc(ch_tmp) = 62 Or Asc(ch_tmp) = 40 Or Asc(ch_tmp) = 41 Or Asc(ch_tmp) = 44 Or Asc(ch_tmp) = 32 Or Asc(ch_tmp) = 46 Or Asc(ch_tmp) = 58 Or Asc(ch_tmp) = 35 Or Asc(ch_tmp) = 42 Then
- TmpMsg = TmpMsg & ch_tmp
- End If
- Next
- str_MSG = TmpMsg.Trim
- Dim i1, i2 As Integer
- i1 = InStr(state.sb.ToString, "<")
- i2 = InStr(state.sb.ToString, ">")
- Dim str_Value As String = Process(str_MSG)
- Console.WriteLine(str_Value)
- If Not str_Value Is Nothing Then
- If str_Value.Length > 1 Then
- Send(handler, str_Value)
- End If
- End If
- state.sb.Remove(0, i2 - 1)
- End If
- handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, New AsyncCallback(AddressOf ReadCallback), state)
- End If
- 'Catch ex As Exception
- ' Console.WriteLine(ex.Message)
- ' Log("Error in Sample Form ReadCallBack function" & ex.Message & Now)
- 'End Try
- End Sub
- Private Shared Sub Send(ByVal handler As Socket, ByVal data As [String])
- 'Try
- Dim byteData As Byte() = Encoding.ASCII.GetBytes(data)
- handler.BeginSend(byteData, 0, byteData.Length, 0, New AsyncCallback(AddressOf SendCallback), handler)
- 'Catch ex As Exception
- ' Console.WriteLine(ex.Message)
- ' Log("Error in Sample Form Send " & ex.Message & " " & Now)
- 'End Try
- End Sub
- Private Shared Sub SendCallback(ByVal ar As IAsyncResult)
- ' Try
- Dim handler As Socket = CType(ar.AsyncState, Socket)
- Dim bytesSent As Integer = handler.EndSend(ar)
- Console.WriteLine(bytesSent.ToString)
- handler.Shutdown(SocketShutdown.Both)
- handler.Close()
- 'Catch e As Exception
- ' Console.WriteLine(e.Message)
- ' Log("Error in Sample Form Sendcallback " & e.Message & " " & Now)
- 'End Try
- End Sub
Expand|Select|Wrap|Line Numbers
- Imports System.Net
- Imports System.Net.Sockets
- Imports System.Threading
- Imports System.Text
- Public Class Form1
- ' The port number for the remote device.
- Private Shared port As Integer = 8001
- ' ManualResetEvent instances signal completion.
- Private Shared connectDone As New ManualResetEvent(False)
- Private Shared sendDone As New ManualResetEvent(False)
- ' The response from the remote device.
- Private Shared response As [String] = [String].Empty
- Dim simid As String
- Dim msg1 As String = "<A," '"<V,1234,AO,,,,,,,,,>" '063514,220207
- Dim msg2 As String = ",1727.9723,7829.4798,0.000>"
- Dim str_date As String
- Dim fn_msg As String
- Public Class StateObject
- ' Client socket.
- Public workSocket As Socket = Nothing
- ' Size of receive buffer.
- Public BufferSize As Integer = 256
- ' Receive buffer.
- Public buffer(256) As Byte
- ' Received data string.
- Public sb As New StringBuilder()
- End Class 'StateObj
- Private Sub StartClient()
- ' Connect to a remote device. 192.168.15.8
- Try
- Dim ipAddress As IPAddress = Net.IPAddress.Parse("192.168.15.8")
- Dim remoteEP As New IPEndPoint(ipAddress, port)
- ' Create a TCP/IP socket.
- Dim client As New Socket(AddressFamily.InterNetwork, _
- SocketType.Stream, ProtocolType.Tcp)
- ' Connect to the remote endpoint.
- client.BeginConnect(remoteEP, AddressOf ConnectCallback, client)
- connectDone.WaitOne()
- ' Send test data to the remote device.
- Send(client, fn_msg)
- sendDone.WaitOne()
- ' Thread.Sleep(1000)
- 'client.Shutdown(SocketShutdown.Both)
- ' client.Close()
- Catch e As Exception
- 'Console.WriteLine(e.ToString())
- Log("Errot In StartClient" & e.Message)
- End Try
- End Sub 'StartClient
- Private Sub ConnectCallback(ByVal ar As IAsyncResult)
- Try
- ' Retrieve the socket from the state object.
- Dim client As Socket = CType(ar.AsyncState, Socket)
- ' Complete the connection.
- client.EndConnect(ar)
- ' Signal that the connection has been made.
- connectDone.Set()
- Catch e As Exception
- Log("Error in connect call back" & e.ToString())
- End Try
- End Sub 'ConnectCallback
- Private Sub Send(ByVal client As Socket, ByVal data As [String])
- Try
- ' 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.
- client.BeginSend(byteData, 0, byteData.Length, 0, _
- AddressOf SendCallback, client)
- Catch ex As Exception
- Log("Error in send " & ex.ToString())
- End Try
- End Sub 'Send
- Private Sub SendCallback(ByVal ar As IAsyncResult)
- Try
- ' Retrieve the socket from the state object.
- Dim client As Socket = CType(ar.AsyncState, Socket)
- ' Complete sending the data to the remote device.
- Dim bytesSent As Integer = client.EndSend(ar)
- ' res = "Sent " & bytesSent & " bytes to server."
- ' Signal that all bytes have been sent.
- sendDone.Set()
- Catch e As Exception
- 'Console.WriteLine(e.ToString())
- Log("Error in send call back" & e.ToString())
- End Try
- End Sub 'SendCallback
- Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
- simid = Trim(InputBox("Enter simid:")) & ","
- msg1 = msg1 & simid
- Timer1.Start()
- End Sub
- Private Sub Timer1_Tick(ByVal sender As Object, ByVal e As System.EventArgs) Handles Timer1.Tick
- str_date = Format(Now().AddMinutes(-330.0), "HHmmss" & "," & "ddMMyy")
- fn_msg = msg1 + str_date + msg2
- StartClient()
- 'Timer1.Stop()
- End Sub
- Public Sub Log(ByVal str_logerr As String)
- Dim fs As New IO.FileStream("C:\ErrorLog.txt", IO.FileMode.Append, IO.FileAccess.Write, IO.FileShare.ReadWrite)
- Dim tw As New IO.StreamWriter(fs)
- tw.WriteLine(str_logerr)
- tw.Close()
- End Sub
- End Class