473,554 Members | 2,920 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Socket Programming

1 New Member
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 3651
setiarakesh
10 New Member
[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
setiarakesh
10 New Member
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

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

Similar topics

1
6324
by: pyguy2 | last post by:
Issues of socket programming can be wierd, so I'm looking for some comments. In my python books I find exclusive use of socket.close(). From my other readings, I know about a "partial close operation". So, I figured it would be useful to post some code about how socket.close() has an implicit send in it and you can actually gain some...
5
3670
by: John Sheppard | last post by:
Hi all, I am not sure that I am posting this in the right group but here it goes anyway. I am new to socket programming and I have been searching on the internet to the questions I am about to pose but have been unsuccessful in finding the answers so far. Either because my understanding of sockets isn't where it needs to be or my questions are...
1
3380
by: John Sheppard | last post by:
Thanks to everyone that responded to my previous Socket Programming question. Now I have run into some behavior that I don't quite understand. Programming environment. VS.NET 2003, C#, Windows XP. About the architecture: I have a socket server dll that contains a class that handles connections for a given local ipaddress and port. This...
5
11670
by: mscirri | last post by:
The code below is what I am using to asynchronously get data from a PocketPC device. The data comes in fine in blocks of 1024 bytes but even when I send no data from the PocketPC constant blocks of 1024 with all values set to Null arrive. Other than examine a block of 1024 to see if the entire block is null, is there any other way to determine...
2
15311
by: djc | last post by:
I read a network programming book (based on framework 1.1) which indicated that you should 'never' use the RecieveTimeout or the SendTimeout 'socket options' on TCP sockets or you may loose data. I now see the socket.RecieveTimeout 'property' in the visual studio 2005 help documentation (framework 2.0) and it has example of it being used with...
10
4012
by: Uma - Chellasoft | last post by:
Hai, I am new to VB.Net programming, directly doing socket programming. In C, I will be able to map the message arrived in a socket directly to a structure. Is this possible in VB.Net. Can anyone please help me with some sample codings and guidance? Can you also suggest some other news group available for socket programming in VB.Net?
11
8584
by: atlaste | last post by:
Hi, In an attempt to create a full-blown webcrawler I've found myself writing a wrapper around the Socket class in an attempt to make it completely async, supporting timeouts and some scheduling mechanisms. I use a non-blocking approach for this, using the call to 'poll' to support the async mechanism - rather than the 'begin' and 'end'...
0
1891
by: shonen | last post by:
I'm currently attempting to connect to a shoutcast server pull down the information from here and then I'll parse it. I got this working with the httplib, which was great, the problem is I want to use the select statement to do only do this periodically. (I'm trying to be a client, accepting data, that might be my first problem) Basically...
8
4666
by: =?Utf-8?B?Sm9obg==?= | last post by:
Hi all, I am new to .net technologies. ASP.NET supports socket programming like send/receive in c or c++? I am developing web-site application in asp.net and code behind is Visual C#. In page_load event, I am using atl com component. Here one for loop is there. In this for loop, number of iterations are 1000, I can receive some data...
3
2758
by: Stuart | last post by:
I am in the process of teaching myself socket programming. I am "playing around" with some simple echo server-client programs for m the book TCP/IP Sockets in C. The Server program is: #include "TCPEchoServer.h" /* TCP echo server includes */ #include <pthread.h /* for POSIX threads */
0
7780
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
1
7530
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
7862
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
6119
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5414
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
3539
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3530
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1994
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
0
812
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

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.