Socket Programming!!!

manasap

Member
Joined
Sep 27, 2007
Messages
5
Programming Experience
Beginner
Hi all!

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

Cordially,
Manasa P
 
Hi..

It would be better if you put your code to your post, so other people can see what might be wrong with your codes.

Regards,
 
hi

I am sending my code.server code is similar to the example given for asynchronous sockets in msdn.Following is the sever code:

VB.NET:
   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

the client program is attached as a zip file.plz find it as an attachment.
please guide me..

cordially,
Manasa P
 

Attachments

  • SimCoreAPP1.0.zip
    14.8 KB · Views: 39
Last edited by a moderator:
server closes connection after sending, this happens at the same time it is either reading or waiting for something to read, either way the read callback will throw.
 
Is it possible to solve this problem?due to this i am losing my data.i want to receive all the packets as every packet is important.How to handle this?please guide me....
 
Well, it's you that is closing it, so don't close it... ??
 
In our case server responds to the requests of the clients with some required data.If i am not closing the socket, I am unable to receive that data.is it possible to receive the response of the server without closing the socket?

cordially,
Manasa P.
 
Yes, the socket is bi-directional, you're already doing that in server.
 
Back
Top