473,586 Members | 2,555 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Need help using tcpClient and tcpListner

I am having trouble using the TcpListener and TcpClient classes.

At the end of this post is server code that runs, and a class whose purpose
is described below.

I need to know when the client closes the connection so I can exit my
listener code. Here is what I have tried.

First I asked MSDN and they said..

TcpClient creates a Socket to send and receive data over a network. Classes
deriving from TcpClient can use this property to get or set this Socket. Use
the underlying Socket returned from Client if you require access beyond that
which TcpClient provides. You can also use Client to set the underlying
Socket to an existing Socket. This might be useful if you want to take
advantage of the simplicity of TcpClient using a pre-existing Socket.

So, I created a class called MyTcpClient, below, that inherited from
TcpClient. I got this code from the MSDN library. Then I changed all
occurances of TcpClient to MyTcpClient in my code. By doing this, I thought I
could then query the property 'IsConnected'.

The idea here is to be able to get at the 'protected connected' property of
the underlying socket.

However, when I try this, the line of code.

tcpCli = tcpList.AcceptT cpClient()

gives this error during the pre compile phase.
C:\Documents and Settings\hcoope r.JOE\My Documents\Visua l Studio
Projects\System NetDemo\TCPList enerForm.vb(140 ): Option Strict On disallows
implicit conversions from 'System.Net.Soc kets.TcpClient' to
'SystemNetDemo. MyTcpClient'.
so I then insert option strict off at the top of my class. The precompiled
error goes away but when it runs, I get the following error.
An unhandled exception of type 'System.Invalid CastException' occured in
SystemNetDemo.e xe
Additional information: Specified cast is not valid.
Any help here???

Hamil.

*************** ********* MyTcpClient class

Imports System.Net.Sock ets

Public Class MyTcpClient

Inherits TcpClient

Public IsConnected As Boolean

Public Sub New()
End Sub 'New

Public Sub UsingProtectedM ethods()

'Uses the protected 'Active' property belonging to the TcpClient
base class
'to determine if a connection is established.
If Me.Active Then
' Calls the protected 'Client' property belonging to the
TcpClient base class.
Dim s As Socket = Me.Client
'Uses the Socket returned by Client to set an option that is not
available using TcpClient.
IsConnected = s.Connected
End If
'To free all resources, calls protected virtual method Dispose
belonging to the TcpClient base class.
Me.Dispose(True )
GC.SuppressFina lize(Me)
End Sub 'UsingProtected Methods

End Class

************ This code runs ........

Imports System.IO
Imports System.net
Imports System.Net.Sock ets
Imports System.Threadin g

Public Class TCPListenerForm
Inherits System.Windows. Forms.Form

Dim listening As Boolean
Dim localhostAddres s As IPAddress
Dim port As Integer
Dim tcpList As TcpListener
Dim tcpCli As TcpClient
Dim ns As NetworkStream
Dim sr As StreamReader
Dim receivedData As String
Dim returnedData As String
Dim sw As StreamWriter

Private Sub btnStart_Click( ByVal sender As System.Object, ByVal e As
System.EventArg s) Handles btnStart.Click
btnStart.Enable d = False
btnStop.Enabled = True
Dim tr As New Thread(AddressO f ListenToClients )
tr.Start()
End Sub

Sub ListenToClients ()
localhostAddres s = IPAddress.Loopb ack
port = CInt(txtPort.Te xt)
tcpList = New TcpListener(loc alhostAddress, port)
tcpList.Start()
listening = True
Do While listening
Do While tcpList.Pending = False And listening = True
Thread.Sleep(10 )
Loop
If Not listening Then Exit Do
Dim tcpCli As New TcpClient
tcpCli = tcpList.AcceptT cpClient()
ns = tcpCli.GetStrea m
sr = New StreamReader(ns )
sw = New StreamWriter(ns )
tbStatus.Text = "connected"
Do While listening = True
Thread.Sleep(10 )
receivedData = sr.ReadLine
If receivedData <> Nothing Then
returnedData = receivedData.To Upper
sw.WriteLine(re turnedData)
sw.Flush()
End If
Loop
sr.Close()
sw.Close()
ns.Close()
tcpCli.Close()
tbStatus.Text = "closed"
Loop
tcpList.Stop()
End Sub

Private Sub btnStop_Click(B yVal sender As System.Object, ByVal e As
System.EventArg s) Handles btnStop.Click
btnStart.Enable d = True
btnStop.Enabled = False
listening = False
End Sub
End Class

Nov 21 '05 #1
1 4524
I am withdrawing this question.
As I have read, even the connect property of the socket doesn't give current
status.
"hamil" wrote:
I am having trouble using the TcpListener and TcpClient classes.

At the end of this post is server code that runs, and a class whose purpose
is described below.

I need to know when the client closes the connection so I can exit my
listener code. Here is what I have tried.

First I asked MSDN and they said..

TcpClient creates a Socket to send and receive data over a network. Classes
deriving from TcpClient can use this property to get or set this Socket. Use
the underlying Socket returned from Client if you require access beyond that
which TcpClient provides. You can also use Client to set the underlying
Socket to an existing Socket. This might be useful if you want to take
advantage of the simplicity of TcpClient using a pre-existing Socket.

So, I created a class called MyTcpClient, below, that inherited from
TcpClient. I got this code from the MSDN library. Then I changed all
occurances of TcpClient to MyTcpClient in my code. By doing this, I thought I
could then query the property 'IsConnected'.

The idea here is to be able to get at the 'protected connected' property of
the underlying socket.

However, when I try this, the line of code.

tcpCli = tcpList.AcceptT cpClient()

gives this error during the pre compile phase.
C:\Documents and Settings\hcoope r.JOE\My Documents\Visua l Studio
Projects\System NetDemo\TCPList enerForm.vb(140 ): Option Strict On disallows
implicit conversions from 'System.Net.Soc kets.TcpClient' to
'SystemNetDemo. MyTcpClient'.
so I then insert option strict off at the top of my class. The precompiled
error goes away but when it runs, I get the following error.
An unhandled exception of type 'System.Invalid CastException' occured in
SystemNetDemo.e xe
Additional information: Specified cast is not valid.
Any help here???

Hamil.

*************** ********* MyTcpClient class

Imports System.Net.Sock ets

Public Class MyTcpClient

Inherits TcpClient

Public IsConnected As Boolean

Public Sub New()
End Sub 'New

Public Sub UsingProtectedM ethods()

'Uses the protected 'Active' property belonging to the TcpClient
base class
'to determine if a connection is established.
If Me.Active Then
' Calls the protected 'Client' property belonging to the
TcpClient base class.
Dim s As Socket = Me.Client
'Uses the Socket returned by Client to set an option that is not
available using TcpClient.
IsConnected = s.Connected
End If
'To free all resources, calls protected virtual method Dispose
belonging to the TcpClient base class.
Me.Dispose(True )
GC.SuppressFina lize(Me)
End Sub 'UsingProtected Methods

End Class

************ This code runs ........

Imports System.IO
Imports System.net
Imports System.Net.Sock ets
Imports System.Threadin g

Public Class TCPListenerForm
Inherits System.Windows. Forms.Form

Dim listening As Boolean
Dim localhostAddres s As IPAddress
Dim port As Integer
Dim tcpList As TcpListener
Dim tcpCli As TcpClient
Dim ns As NetworkStream
Dim sr As StreamReader
Dim receivedData As String
Dim returnedData As String
Dim sw As StreamWriter

Private Sub btnStart_Click( ByVal sender As System.Object, ByVal e As
System.EventArg s) Handles btnStart.Click
btnStart.Enable d = False
btnStop.Enabled = True
Dim tr As New Thread(AddressO f ListenToClients )
tr.Start()
End Sub

Sub ListenToClients ()
localhostAddres s = IPAddress.Loopb ack
port = CInt(txtPort.Te xt)
tcpList = New TcpListener(loc alhostAddress, port)
tcpList.Start()
listening = True
Do While listening
Do While tcpList.Pending = False And listening = True
Thread.Sleep(10 )
Loop
If Not listening Then Exit Do
Dim tcpCli As New TcpClient
tcpCli = tcpList.AcceptT cpClient()
ns = tcpCli.GetStrea m
sr = New StreamReader(ns )
sw = New StreamWriter(ns )
tbStatus.Text = "connected"
Do While listening = True
Thread.Sleep(10 )
receivedData = sr.ReadLine
If receivedData <> Nothing Then
returnedData = receivedData.To Upper
sw.WriteLine(re turnedData)
sw.Flush()
End If
Loop
sr.Close()
sw.Close()
ns.Close()
tcpCli.Close()
tbStatus.Text = "closed"
Loop
tcpList.Stop()
End Sub

Private Sub btnStop_Click(B yVal sender As System.Object, ByVal e As
System.EventArg s) Handles btnStop.Click
btnStart.Enable d = True
btnStop.Enabled = False
listening = False
End Sub
End Class

Nov 21 '05 #2

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

Similar topics

2
1313
by: Tom Rahav | last post by:
Hello All! I need to extract Socket object from a TcpClient object, in order to get client's IP address. I've found the following article that describes how to derive from TcpClient class and use the Client property (that I need so much...!)....
5
33837
by: Greg Martz | last post by:
I'd like to do the following in C# and prefer using tcpclient rather than raw sockets... Connect to a unix box Login run date +%H%M%S retrieve the response. That's it, nothing more. This shouldn't be too complicated, I thought... I have yet to find any examples of being able to do this.
1
1053
by: mEEEEE | last post by:
I want to transfer n number of binary files from a server to a client one by one. I am using TcpListener and TcpClient. Any suggestions? mE
0
1958
by: Torsten Brasch | last post by:
Hi All and Happy New Year ;) I have a very strange problem with System.Net.Sockets.TcpClient(). For some reason, the number of bytes I can receive is limited to 5460 bytes. I made sure that the server really sends everything I expect it to send. I am actually sending XML messages and this limit is a pain in the ... Here is the code:...
1
8371
by: Chin Fui | last post by:
I am now doing my final year project using VB.NET. The project is about implement a multiplayer network game. But now I am stuck in the connection part, no idea in how to start to write the network application. Hope anyone can give me any hint or help... Thank you... Chin Fui
3
4437
by: Terry Olsen | last post by:
I want to have an array of class objects that raise an event when a condition is true. Like so... ------------------------------------------------------- Public Class ClientHandler Public Event DataArrival(ByVal client As TcpClient) Public Writer As BinaryWriter Public Reader As BinaryReader Private myClient As TcpClient
2
4053
by: Terry Olsen | last post by:
Hoping someone can help me here. I've got this code written, and it works fine for the first connection. But if I connect another client (while the first is still connected), I get connected but nothing else, no data exchange. If I disconnect the 2nd session, I get a System.IO.IOException. If I disconnect the first session with the 2nd...
5
4793
by: Nobody | last post by:
Hi all, I try to write a small client that can handle some TCP communication message. I was wondering how I could use the TcpClient class to manage it. At the first time, I don't want to play with the async methods. My main issue is related about receiving informations back from the server. How can I be sure that the server has...
0
1366
by: sternr | last post by:
Hey, I'm using a TcpClient to create HTTP requests to my web-server (I know of HttpWebRequest, it is mandatory for me to use TcpClient.). Here's my code: TcpClient tcp = new TcpClient(SERVER_IP, SERVER_PORT); tcp.NoDelay = true; string data = "GET http://" + SERVER_IP + SERVER_PORT + "/getData?id=1
0
8202
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. ...
0
8338
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7959
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
6614
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...
0
5390
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...
0
3837
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
3865
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1449
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1180
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.