472,146 Members | 1,470 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,146 software developers and data experts.

Socket Programming

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

I am sending the code.


SERVER
Expand|Select|Wrap|Line Numbers
  1. Imports System
  2. Imports System.Math
  3. Imports System.Text
  4. Imports System.Threading
  5. Imports System.Net
  6. Imports System.Net.Sockets
  7.  
  8. Module Module1
  9.  
  10.     ' Global variables Section
  11.  
  12.     Dim str_Insert1, str_Insert2 As String
  13.     Dim Sim_Veh_ID As Int64 = 0
  14.     Dim str_select_simvehid As Int64 = 0
  15.     Dim Str_Select_EmpID As String = ""
  16.     Dim Str_Select_Mobile As String = ""
  17.     Dim Dbl_Prev_Long, Dbl_Prev_Lat As Double
  18.     Dim Dbl_Total_Dist As Double = 0
  19.     Dim Str_Select_TripID As String
  20.     Dim Dbl_Emp_Long, Dbl_Emp_Lat, Dbl_Emp_Dist As Double
  21.  
  22.     Sub Main()
  23.         ' Try
  24.         If Path() Then
  25.             AsynchronousSocketListener.StartListening()
  26.         End If
  27.         ' Catch ex As Exception
  28.         'Console.WriteLine(ex.Message)
  29.         'Log("Error in Main Function " & ex.Message & Now)
  30.         'End Try
  31.     End Sub
  32.  
  33.     Public Class StateObject
  34.         Public workSocket As Socket = Nothing
  35.         Public Const BufferSize As Integer = 200
  36.         Public buffer(BufferSize) As Byte
  37.         Public sb As New StringBuilder
  38.     End Class
  39.  
  40.     Public Class AsynchronousSocketListener
  41.         Public Shared data As String = Nothing
  42.         Public Shared allDone As New ManualResetEvent(False)
  43.         Shared str_Error As String
  44.  
  45.  
  46.         Public Shared Sub StartListening()
  47.             ' Try
  48.             Dim bytes() As Byte = New [Byte](1024) {}
  49.             Dim ipHostInfo As IPHostEntry = Dns.GetHostEntry(Dns.GetHostName())
  50.             Dim ipAddress As IPAddress = ipHostInfo.AddressList(0)
  51.             Dim localEndPoint As New IPEndPoint(ipAddress, str_Port)
  52.             Dim listener As New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
  53.             'Try
  54.             listener.Bind(localEndPoint)
  55.             listener.Listen(1000)
  56.             While True
  57.                 allDone.Reset()
  58.                 Console.WriteLine("Waiting for a connection... on Port No:")
  59.                 Console.WriteLine(localEndPoint)
  60.                 listener.BeginAccept(New AsyncCallback(AddressOf AcceptCallback), listener)
  61.                 allDone.WaitOne()
  62.             End While
  63.             ' Catch e As Exception
  64.             'Console.WriteLine(E.Message)
  65.             'Log("Error in Sample Form StartListening Second try " & E.Message & Now)
  66.             ''  End Try
  67.             'Console.WriteLine(ControlChars.Cr + "Press ENTER to continue...")
  68.             'Console.Read()
  69.             '' Catch ex As Exception
  70.             'Console.WriteLine(ex.Message)
  71.             'Log("Error in Sample Form StartListening First Try " & ex.Message & Now)
  72.             'End Try
  73.         End Sub
  74.  
  75.         Public Shared Sub AcceptCallback(ByVal ar As IAsyncResult)
  76.             ' Try
  77.             allDone.Set()
  78.             Dim listener As Socket = CType(ar.AsyncState, Socket)
  79.             Dim handler As Socket = listener.EndAccept(ar)
  80.             Dim state As New StateObject
  81.             state.workSocket = handler
  82.             Console.WriteLine("Connection Established........")
  83.             handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, New AsyncCallback(AddressOf ReadCallback), state)
  84.             'Catch ex As Exception
  85.             '    Console.WriteLine(ex.Message)
  86.             '    Log("Error in Sample Form Acceptcallback " & ex.Message & Now)
  87.             'End Try
  88.         End Sub
  89.  
  90.         Public Shared Sub ReadCallback(ByVal ar As IAsyncResult)
  91.             '  Try
  92.             Dim state As StateObject = CType(ar.AsyncState, StateObject)
  93.             Dim handler As Socket = state.workSocket
  94.             Dim bytesRead As Integer
  95.             bytesRead = state.sb.Capacity
  96.             bytesRead = handler.EndReceive(ar)
  97.             If bytesRead > 0 Then
  98.                 state.sb.Append(Encoding.Default.GetString(state.buffer, 0, bytesRead))
  99.                 state.sb.Replace(" ", "")
  100.                 state.sb.Replace(Chr(13), "")
  101.                 state.sb.Replace(vbCr, "")
  102.                 If InStr(state.sb.ToString, "<") > 0 And InStr(state.sb.ToString, ">") > 0 Then
  103.                     Dim str_MSG As String
  104.                     str_MSG = state.sb.ToString.Trim
  105.                     Console.WriteLine(str_MSG)
  106.                     Dim ch_tmp, TmpMsg As String
  107.                     str_MSG = Mid(str_MSG, InStr(str_MSG, "<"), InStr(str_MSG, ">"))
  108.                     ch_tmp = str_MSG
  109.                     TmpMsg = ""
  110.                     For i As Integer = 1 To Len(str_MSG)
  111.                         ch_tmp = ""
  112.                         ch_tmp = Mid(str_MSG, i, 1)
  113.                         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
  114.                             TmpMsg = TmpMsg & ch_tmp
  115.                         End If
  116.                     Next
  117.                     str_MSG = TmpMsg.Trim
  118.                     Dim i1, i2 As Integer
  119.                     i1 = InStr(state.sb.ToString, "<")
  120.                     i2 = InStr(state.sb.ToString, ">")
  121.                     Dim str_Value As String = Process(str_MSG)
  122.                     Console.WriteLine(str_Value)
  123.                     If Not str_Value Is Nothing Then
  124.                         If str_Value.Length > 1 Then
  125.                             Send(handler, str_Value)
  126.                         End If
  127.                     End If
  128.                     state.sb.Remove(0, i2 - 1)
  129.                 End If
  130.                 handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, New AsyncCallback(AddressOf ReadCallback), state)
  131.             End If
  132.             'Catch ex As Exception
  133.             '    Console.WriteLine(ex.Message)
  134.             '    Log("Error in Sample Form ReadCallBack function" & ex.Message & Now)
  135.             'End Try
  136.         End Sub
  137.  
  138.         Private Shared Sub Send(ByVal handler As Socket, ByVal data As [String])
  139.             'Try
  140.             Dim byteData As Byte() = Encoding.ASCII.GetBytes(data)
  141.             handler.BeginSend(byteData, 0, byteData.Length, 0, New AsyncCallback(AddressOf SendCallback), handler)
  142.             'Catch ex As Exception
  143.             '    Console.WriteLine(ex.Message)
  144.             '    Log("Error in Sample Form Send " & ex.Message & " " & Now)
  145.             'End Try
  146.         End Sub
  147.  
  148.         Private Shared Sub SendCallback(ByVal ar As IAsyncResult)
  149.             ' Try
  150.             Dim handler As Socket = CType(ar.AsyncState, Socket)
  151.             Dim bytesSent As Integer = handler.EndSend(ar)
  152.             Console.WriteLine(bytesSent.ToString)
  153.             handler.Shutdown(SocketShutdown.Both)
  154.             handler.Close()
  155.             'Catch e As Exception
  156.             '    Console.WriteLine(e.Message)
  157.             '    Log("Error in Sample Form Sendcallback " & e.Message & " " & Now)
  158.             'End Try
  159.         End Sub
  160.  
CLIENT
Expand|Select|Wrap|Line Numbers
  1. Imports System.Net
  2. Imports System.Net.Sockets
  3. Imports System.Threading
  4. Imports System.Text
  5.  
  6. Public Class Form1
  7.  
  8.     ' The port number for the remote device.
  9.     Private Shared port As Integer = 8001
  10.  
  11.     ' ManualResetEvent instances signal completion.
  12.     Private Shared connectDone As New ManualResetEvent(False)
  13.     Private Shared sendDone As New ManualResetEvent(False)
  14.  
  15.     ' The response from the remote device.
  16.     Private Shared response As [String] = [String].Empty
  17.     Dim simid As String
  18.     Dim msg1 As String = "<A," '"<V,1234,AO,,,,,,,,,>" '063514,220207
  19.     Dim msg2 As String = ",1727.9723,7829.4798,0.000>"
  20.     Dim str_date As String
  21.  
  22.     Dim fn_msg As String
  23.  
  24.  
  25.     Public Class StateObject
  26.         ' Client socket.
  27.         Public workSocket As Socket = Nothing
  28.         ' Size of receive buffer.
  29.         Public BufferSize As Integer = 256
  30.         ' Receive buffer.
  31.         Public buffer(256) As Byte
  32.         ' Received data string.
  33.         Public sb As New StringBuilder()
  34.     End Class 'StateObj
  35.  
  36.     Private Sub StartClient()
  37.         ' Connect to a remote device.  192.168.15.8
  38.         Try
  39.             Dim ipAddress As IPAddress = Net.IPAddress.Parse("192.168.15.8")
  40.             Dim remoteEP As New IPEndPoint(ipAddress, port)
  41.  
  42.             '  Create a TCP/IP socket.
  43.             Dim client As New Socket(AddressFamily.InterNetwork, _
  44.                 SocketType.Stream, ProtocolType.Tcp)
  45.  
  46.             ' Connect to the remote endpoint.
  47.             client.BeginConnect(remoteEP, AddressOf ConnectCallback, client)
  48.             connectDone.WaitOne()
  49.             ' Send test data to the remote device.
  50.  
  51.             Send(client, fn_msg)
  52.             sendDone.WaitOne()
  53.  
  54.             ' Thread.Sleep(1000)
  55.  
  56.             'client.Shutdown(SocketShutdown.Both)
  57.             ' client.Close()
  58.  
  59.         Catch e As Exception
  60.             'Console.WriteLine(e.ToString())
  61.             Log("Errot In StartClient" & e.Message)
  62.  
  63.         End Try
  64.     End Sub 'StartClient
  65.  
  66.  
  67.     Private Sub ConnectCallback(ByVal ar As IAsyncResult)
  68.         Try
  69.             ' Retrieve the socket from the state object.
  70.             Dim client As Socket = CType(ar.AsyncState, Socket)
  71.  
  72.             ' Complete the connection.
  73.             client.EndConnect(ar)
  74.  
  75.             ' Signal that the connection has been made.
  76.             connectDone.Set()
  77.         Catch e As Exception
  78.  
  79.             Log("Error in connect call back" & e.ToString())
  80.         End Try
  81.     End Sub 'ConnectCallback
  82.  
  83.  
  84.     Private Sub Send(ByVal client As Socket, ByVal data As [String])
  85.         Try
  86.             ' Convert the string data to byte data using ASCII encoding.
  87.  
  88.             Dim byteData As Byte() = Encoding.ASCII.GetBytes(data)
  89.  
  90.             ' Begin sending the data to the remote device.
  91.             client.BeginSend(byteData, 0, byteData.Length, 0, _
  92.                 AddressOf SendCallback, client)
  93.  
  94.         Catch ex As Exception
  95.             Log("Error in send " & ex.ToString())
  96.         End Try
  97.     End Sub 'Send
  98.  
  99.  
  100.     Private Sub SendCallback(ByVal ar As IAsyncResult)
  101.         Try
  102.             ' Retrieve the socket from the state object.
  103.             Dim client As Socket = CType(ar.AsyncState, Socket)
  104.  
  105.             ' Complete sending the data to the remote device.
  106.             Dim bytesSent As Integer = client.EndSend(ar)
  107.  
  108.             ' res = "Sent " & bytesSent & " bytes to server."
  109.  
  110.             ' Signal that all bytes have been sent.
  111.             sendDone.Set()
  112.  
  113.  
  114.         Catch e As Exception
  115.             'Console.WriteLine(e.ToString())
  116.             Log("Error in send call back" & e.ToString())
  117.         End Try
  118.     End Sub 'SendCallback
  119.  
  120.     Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
  121.         simid = Trim(InputBox("Enter simid:")) & ","
  122.         msg1 = msg1 & simid
  123.  
  124.         Timer1.Start()
  125.     End Sub
  126.  
  127.     Private Sub Timer1_Tick(ByVal sender As Object, ByVal e As System.EventArgs) Handles Timer1.Tick
  128.         str_date = Format(Now().AddMinutes(-330.0), "HHmmss" & "," & "ddMMyy")
  129.         fn_msg = msg1 + str_date + msg2
  130.         StartClient()
  131.         'Timer1.Stop()
  132.     End Sub
  133.  
  134.     Public Sub Log(ByVal str_logerr As String)
  135.         Dim fs As New IO.FileStream("C:\ErrorLog.txt", IO.FileMode.Append, IO.FileAccess.Write, IO.FileShare.ReadWrite)
  136.         Dim tw As New IO.StreamWriter(fs)
  137.         tw.WriteLine(str_logerr)
  138.         tw.Close()
  139.     End Sub
  140.  
  141.  
  142. End Class
Sep 27 '07 #1
2 3476
[HTML]This error occurs when server recieves ZERO byte length .It means that your cleint has closed.Then this error occur

Kindly tell me what is the operatng system you are using for Server[/HTML]
Dec 15 '07 #2
Sinec i am also working on the same problem when the rate of data transfer is very high from vclient to server . When client Socket request is pending for a long time then it happens .This is usually done by increasing the parameter value in que function.But there is limitation of this only upto 1000. and i have tested this also by setting the 100,000 in Que function and it did not work .

The only factor which i think that may work is to write the server socket in such a manner that none of the client socket had to wait for longer period to remain in que of server socket main object listening the client.Increase the number of threads accordingly to process the Data which reaches at server from client on the main socket.

I describe you what i faced in socket programme. I have requirement of large (say more than 100) clients to be connected to one server socket object that is the main socket object to listen the clients that open child sockets in asychronous manner.And the network is GPRS for Cleint(GSM Modem that open socket client and connect to server) and server in LAN is with Static IP ,port and Port opened in Firewall which routed to a PC (Where the Socket server is running ) with IP and and socket port

As i was also facing the problem of disconnecting and after this when client again tried to connect to server then server did not connect to it and there was no error in client programme.Then to sort the problem of reconnectivity i had to call the listening function of main listeting socket in socketServer again and again at regular interval of time in timer and also at the time when any client socket is disconnected. And my problem is sorted out. And the capacity of Server is raised to 70 Cleints and in each second these 70 clients are sending 5 string of 1024 byte length in 1 second( ie. one string in 20 milli seconds).
and my Server is stable and processing the strings at very faster rate.

and also i tell you when string reaches on server then it is splitted and saved into SQL Server Data Base by opening one connection object of SqlClient and using the procedure to save the data into Data base.This connection is one time declared on form load of window in C#

Now i am stucked. As i inrease the number of clients(GSM Socket) to connect to server then it stops recieving the strings from the Cleints and one by one all cleints go down and i recieve an error remote socket disconnected forcibly and cPU show 100 % usage in Task Manager as well . But when i open another port and run the another instance of same programme on the Same machine then i am able to connect more than 70 clients. CPU usage goes down and do not show 100 % usage .It means my Server is capable to listen and process only 70 Clients(GSM Modem) .

And i want to increase the number of clients on the server . so that i do not need to open more ports on the Same machine as well in Firewall.

i conclude this that if we can free the que of server socket with requests pending from client then it can happen. So try to open more threads so that strings which are recieved on server socket from Client Socket can be processed in parallel manner and CPU usage can be optimized.This was i think can be sorted out

Kindly let me know if you get success

Rakesh Setia

[ email addresses snipped; - mod ]
Dec 23 '07 #3

Post your reply

Sign in to post your reply or Sign up for a free account.

Similar topics

1 post views Thread by pyguy2 | last post: by
5 posts views Thread by John Sheppard | last post: by
1 post views Thread by John Sheppard | last post: by
2 posts views Thread by djc | last post: by
11 posts views Thread by atlaste | last post: by
8 posts views Thread by =?Utf-8?B?Sm9obg==?= | last post: by
3 posts views Thread by Stuart | last post: by
reply views Thread by Saiars | last post: by
reply views Thread by leo001 | last post: by

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.