473,699 Members | 2,701 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Socket still sending?

Hello Fellow Developer,

I use the System.Net.Sock ets to send/receive data (no
tcpclient/tcplistener), I made a receivethread in my wrapper, the
receivethread loops/sleeps while waiting for data and then fires a
datareceived event.
Within the waitingloop there is a timeout function, but I want the the
'last-time-socket-used' variable set when the socket is finished sending.
When I send by System.Net.Sock ets.Socket.Send (buffer()) (<--this can be
10Mb) then it imitially returns to my thread, so the (internal) Send
functions buffers it. I tried to Poll, but this only tells you if you could
write to the socket, and I tried the getSocketOption (Tried
Socket/TCP/IP,Tried
SendBuffer/ReceiveBuffer/SendLowWater/ReceiveLowWater/SendTimeout/ReceiveTim
eout) but that throws an Error. (Before u look in my code I would like to
explain that I want to catch all exceptions in the parent object.)

Regards,
Robert

Ok this is myconnectioncla ss.vb

Imports System
Imports System.Net
Imports System.Net.Sock ets
Imports System.IO
Imports System.Collecti ons
Imports System.Threadin g
Imports System.Diagnost ics

Public Class SmartConnection
Public Event ConnectionOpene d(ByVal pMe As SmartConnection )
Public Event DataReceived(By Val pMe As SmartConnection , ByVal Data As
Message)
Public Event CouldntConnect( ByVal pMe As SmartConnection )
Public Event ConnectionClose d(ByVal pMe As SmartConnection )
Public Event [Error](ByVal pMe As SmartConnection , ByVal pErr As
Exception)
Public Event TimeOut(ByVal pme As SmartConnection )

Private _Socket As Socket
Private _ReadThread As Thread
Private _StopThread As Thread 'Lookup threadingpool
Private _Closing As Boolean = False
Private _InError As Boolean = False
Private _lport As Long
Private lasttimeout As Long
Private pHost As String
Private pPort As Long
Private pRead As Boolean
Private pTimeout As Long
Private _Iswriting As Boolean = False

Protected Overrides Sub Finalize()
_ReadThread = Nothing
_StopThread = Nothing
_Socket = Nothing
MyBase.Finalize ()
End Sub

#Region " Properties"
Public ReadOnly Property IsClosing() As Boolean
Get
IsClosing = (_Closing Or _Socket Is Nothing)
End Get
End Property

Public ReadOnly Property Connected() As Boolean
Get
Try
Connected = ((Not IsClosing) AndAlso _Socket.Connect ed =
True)
Catch e As Exception
OnError(e)
End Try
End Get
End Property

Protected ReadOnly Property Receiving() As Boolean
Get
Try
If Not Connected Then Throw New Exception("Sock et is not
connected")
Receiving = ((Not _ReadThread Is Nothing) AndAlso
_ReadThread.IsA live)
Catch e As Exception
OnError(e)
End Try
End Get
End Property

Public ReadOnly Property IPlocal() As String
Get
Try
If Connected Then IPlocal = EP2IPS(_Socket. LocalEndPoint)
Catch e As Exception
OnError(e)
End Try
End Get
End Property

Public ReadOnly Property IPremote() As String
Get
Try
If Connected Then IPremote = EP2IPS(_Socket. RemoteEndPoint)
Catch e As Exception
OnError(e)
End Try
End Get
End Property
#End Region
#Region " Connect"
Public Overridable Sub ConnectTo(ByRef hostName As String, ByRef port As
Long, Optional ByVal timeout As Long = 0)
Try
StartConnect(ho stName, port, timeout, True)
Catch e As Exception
OnError(e)
End Try
End Sub

Protected Sub ConnectToWithou tReading(ByRef hostName As String, ByRef
port As Long, Optional ByVal timeout As Long = 0)
Try
StartConnect(ho stName, port, timeout, False)
Catch e As Exception
OnError(e)
End Try
End Sub

Private Sub StartConnect(By Ref hostName As String, ByRef port As Long,
ByRef timeout As Long, ByRef read As Boolean)
Try
If Not _ReadThread Is Nothing Then Throw New Exception("Alre ady
trying to connect")
_ReadThread = New Thread(AddressO f ConnectThread)
pHost = hostName : pPort = port : pRead = read : pTimeout =
timeout
_ReadThread.Sta rt()
Catch e As Exception
OnError(e)
End Try
End Sub

Private Sub ConnectThread()
Try
If pHost = "" Then Throw New ArgumentNullExc eption("hostnam e")
If pPort < IPEndPoint.MinP ort Or pPort > IPEndPoint.MaxP ort Then
Throw New ArgumentOutOfRa ngeException("p ort", "ArgRange_Port" )
_Socket = New Socket(AddressF amily.InterNetw ork,
SocketType.Stre am, ProtocolType.Tc p)
Try
_Socket.Connect (New
IPEndPoint(Dns. Resolve(pHost). AddressList(0), pPort))
_lport = CType(_Socket.L ocalEndPoint,
System.Net.IPEn dPoint).Port
If Not pRead Then
SetReadName("SC .Read[PreConnect]")
_ReadThread = Nothing
Else
SetReadName("SC .EarlyRead[" & _lport & "]")
End If
OnConnectionOpe ned()
If pRead Then Receive()
Catch e As SocketException 'e.ErrorCode = 10061
SetReadName("SC .Read[NoConnect]")
_ReadThread = Nothing
OnCouldntConnec t()
Close()
End Try
Catch e As Exception
SetReadName("SC .Read[Error]")
_ReadThread = Nothing
OnError(e)
End Try
End Sub
#End Region
#Region " Receive"
Protected Sub StartReceive()
Try
If Receiving Then Throw New Exception("Rece iving was already
started")
_ReadThread = New Thread(AddressO f Receive)
SetReadName("SC .LateRead[" & _lport & "]")
_ReadThread.Sta rt()
Catch e As Exception
OnError(e)
End Try
End Sub

Private Sub Receive()
Dim i As Long
Dim b() As Byte
'Dim ds As String, dt As String
Try
Do While Connected
If pTimeout > 0 Then lasttimeout = CurrTick() + pTimeout
Do While _Socket.Availab le = 0
'dt = ds
'ds = "@" & _lport & ","
'ds += _Socket.GetSock etOption(Socket OptionLevel.Soc ket,
SocketOptionNam e.SendBuffer) & ","
'ds += _Socket.GetSock etOption(Socket OptionLevel.Soc ket,
SocketOptionNam e.SendLowWater) & ","
'ds += _Socket.GetSock etOption(Socket OptionLevel.Soc ket,
SocketOptionNam e.SendTimeout)
'Debug.WriteLin eIf(dt <> ds, ds)
_ReadThread.Sle ep(ReceiveWait)
If IsClosing Then Exit Sub
If _Socket.Poll(0, SelectMode.Sele ctError) Then

'System.Runtime .InteropService s.Marshal.GetLa stWin32Error())
'_Socket.GetSoc ketOption(Socke tOptionLevel.IP ,
SocketOptionNam e.Error)
OnError(New Exception("Sock et Error"))
End If
If pTimeout > 0 Then
'If _Socket.Poll(0, SelectMode.Sele ctWrite) Then
'lasttimeout = CurrTick() + pTimeout
'Else
If lasttimeout <= CurrTick() Then
OnTimeOut()
Close()
Exit Sub
End If
'Endif
End If
Loop
ReDim b(_Socket.Avail able - 1)
'SyncLock _Socket
i = _Socket.Receive (b, SocketFlags.Non e)
'End SyncLock
If i <> b.Length Then Throw New
Exception("Sock et-data-length differs")
If i = 0 Then Throw New Exception("Sock et-data-length = 0")
OnMessageReceiv ed(New Message(b))
b = Nothing
Loop
Catch e As Exception
OnError(e)
End Try
End Sub
#End Region
#Region " Send"
Public Overridable Overloads Sub Send(ByRef data As String)
Try
Send(getbytes(d ata))
Catch e As Exception
OnError(e)
End Try
End Sub

Public Overridable Overloads Sub Send(ByRef data() As Byte)
Try
If Not Connected Then Throw New Exception("Sock et isn't
connected")
_Iswriting = True
'SyncLock _Socket
_Socket.Send(da ta)
'End SyncLock
_Iswriting = False
Catch e As Exception
_Iswriting = False
OnError(e)
End Try
End Sub
#End Region
#Region " Close"
Public Overridable Sub Close() 'OR QUEE IT?
Try
If IsClosing Then Throw New Exception("Alre ady is closing")
_Closing = True
_StopThread = New Thread(AddressO f DoClose)
_StopThread.Nam e = "SC.Stop[" & _lport & "]"
_StopThread.Sta rt()
Catch e As Exception
OnError(e)
End Try
End Sub

Private Sub DoClose()
Try
_StopThread.Sle ep(CloseWait)
Try
If Not _ReadThread Is Nothing Then
SetReadName("SC .Read[Close]")
If _ReadThread.IsA live Then _ReadThread.Abo rt()
End If
Catch e As Exception
End Try
Try
If Not _Socket Is Nothing AndAlso _Socket.Connect ed Then
_Socket.Close()
Catch e As Exception
End Try
_ReadThread = Nothing
_Socket = Nothing
_Closing = False
_StopThread = Nothing
OnConnectionClo sed()
Catch e As Exception
OnError(e)
End Try
End Sub
#End Region
#Region " OnEvent"
Protected Sub OnError(ByRef pErr As Exception) 'If 2 errors in diff
threads?
Debug.WriteLine (pErr.Message)
Debug.WriteLine (pErr.StackTrac e)
Try
If Not _InError Then
_InError = True
Close()
_InError = False
End If
RaiseEvent Error(Me, pErr)
Catch e As Exception
Throw e
End Try
End Sub

Protected Sub OnTimeOut()
Try
RaiseEvent TimeOut(Me)
Catch e As Exception
OnError(e)
End Try
End Sub

Protected Sub OnCouldntConnec t()
Try
RaiseEvent CouldntConnect( Me)
Catch e As Exception
OnError(e)
End Try
End Sub

Protected Sub OnConnectionClo sed()
Try
RaiseEvent ConnectionClose d(Me)
Catch e As Exception
OnError(e)
End Try
End Sub

Protected Sub OnConnectionOpe ned()
Try
RaiseEvent ConnectionOpene d(Me)
Catch e As Exception
OnError(e)
End Try
End Sub

Protected Sub OnMessageReceiv ed(ByRef data As Message)
Try
RaiseEvent DataReceived(Me , data)
Catch e As Exception
OnError(e)
End Try
End Sub
#End Region

Private Sub SetReadName(ByR ef pName As String)
If Not _ReadThread Is Nothing AndAlso _ReadThread.Nam e Is Nothing
Then _ReadThread.Nam e = pName
End Sub

End Class
Nov 15 '05 #1
3 4631
Hi Robert,

Are you using Blocking or Non-Blocking mode?
AFAIK when used in blocking mode the method is blocked till it finishes.
Other solution would be to try asnyc sending..

Miha
Nov 15 '05 #2
Hello Miha,

Thanks for your reaction.

I tried _Socket.Blockin g = True in the sub ConnectThread. But this made no
differends.

With asnyc sending (BeginSend..End Send), After the async callsback the
socket is still sending (even if blocking is on)

Regards, Robert

"Miha Markic" <mi***@spin.NO. SPAM.si> schreef in bericht
news:%2******** ********@TK2MSF TNGP10.phx.gbl. ..
Hi Robert,

Are you using Blocking or Non-Blocking mode?
AFAIK when used in blocking mode the method is blocked till it finishes.
Other solution would be to try asnyc sending..

Miha

Nov 15 '05 #3
The code for async is this:

Private Sub SendFinish(ByVa l pia As System.IAsyncRe sult)
Try
If Not Connected Then Throw New Exception("Sock et isn't
connected")
Dim i As Long = _Socket.EndSend (pia)
_Iswriting = False
Catch e As Exception
_Iswriting = False
OnError(e)
End Try
End Sub

Public Overridable Overloads Sub Send(ByRef data() As Byte)
Try
If Not Connected Then Throw New Exception("Sock et isn't
connected")
'A data arrival can be faster then the syncthread
Thread.CurrentT hread.Sleep(500 ) 'This is probally _ReadThread
If _Iswriting Then Throw New Exception("Alre ady sending")
_Iswriting = True 'Cant write more then once!! TX/RC/RC/TX no
RC/TX/TX/RC
'SyncLock _Socket
'_Socket.Send(d ata)
_Socket.BeginSe nd(data, 0, data.Length, SocketFlags.Non e,
AddressOf SendFinish, Nothing)
'End SyncLock
'_Iswriting = False
Catch e As Exception
'_Iswriting = False
OnError(e)
End Try
End Sub

"Robert A. van Ginkel" <ro****@stylega te.com> schreef in bericht
news:Om******** ******@TK2MSFTN GP10.phx.gbl...
Hello Miha,

Thanks for your reaction.

I tried _Socket.Blockin g = True in the sub ConnectThread. But this made no
differends.

With asnyc sending (BeginSend..End Send), After the async callsback the
socket is still sending (even if blocking is on)

Regards, Robert

"Miha Markic" <mi***@spin.NO. SPAM.si> schreef in bericht
news:%2******** ********@TK2MSF TNGP10.phx.gbl. ..
Hi Robert,

Are you using Blocking or Non-Blocking mode?
AFAIK when used in blocking mode the method is blocked till it finishes.
Other solution would be to try asnyc sending..

Miha


Nov 15 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
11860
by: Stephan Steiner | last post by:
Hi The project I'm currently working on involves sending large UDP broadcasts. As the .NET framework already provides an easy facility for sending and receiving UDP packets I thought it was a good idea to use UdpClient rather than sockets directly. A few weeks back I ended up rewriting the receiver part to use sockets directly because I had to manipulate some low level socket properties, and those manipulations would fail on the...
3
3697
by: Robert A. van Ginkel | last post by:
In news:OZ0W9RsdDHA.2432@TK2MSFTNGP10.phx.gbl... I ask the question how I can see if all the data is on the other side of the connection. I got as answer that I should use the blocking property. I tried this I don't see any diffents, I am sending 10Mb and the Send/BeginSend command doesn't wait till the data is on the remotepoint. Can somebody pls. explain this. Regards Robert.
4
18120
by: Chris Tanger | last post by:
Context: C# System.Net.Sockets Socket created with constructor prarmeters Internetwork, Stream and TCP everything else is left at the default parameters and options except linger may be changed as I find appropriate. I am using the socket asynchronously by calling the BeingSend and BeginReceive calls. I would like to be able to call shutdown and close asynchronously if possible.
3
11332
by: Sells, Fred | last post by:
I'm using MSW XP Pro with Python 2.4 to develop but production will be Linux with Python 2.3. (could upgrade to 2.4 if absolutely necessary) I can also switch to Linux for development if necessary. I am writing some python to replace proprietary software that talks to a timeclock via UDP. The timeclock extracts the sending port from the UDP header and uses that for all response messages.
9
3599
by: Macca | last post by:
Hi, I have a synchronous socket server which my app uses to read data from clients. To test this I have a simulated client that sends 100 byte packets. I have set up the socket server so that its buffer is bigger than this. I did this expecting the data to be read in one pass.
3
4301
by: BuddyWork | last post by:
Hello, Could someone please explain why the Socket.Send is slow to send to the same process it sending from. Eg. Process1 calls Socket.Send which sends to the same IP address and port, the receiver is running within Process1. If I move the receiver into Process2 then its fast. Please can someone explain.
0
3161
by: Buddy Home | last post by:
There is two examples of code. Example 1. Send and Receive within the same process. Put this code in a console app called SendAndReceive and run the code. using System; using System.Collections.Generic; using System.Net; using System.Net.Sockets; using System.Runtime.Serialization.Formatters.Binary;
2
3668
by: manasap | last post by:
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
1
7159
by: keksy | last post by:
Hi every1, I am writing a small client/server application and in it I want to send an image asynchronous from the client to the server through a TCP socket. I found an example code on the MSDN site, which is actually for sending strings. I tried to adapt this code so that the client sends an image instead of a string. However, there is something wrong on the server side (i guess)... The server starts listening, the client starts sending...
0
8686
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9173
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. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8882
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 choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6533
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 instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5872
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4375
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 the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4627
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3057
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
2
2345
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.