473,232 Members | 1,649 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

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

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.AcceptTcpClient()

gives this error during the pre compile phase.
C:\Documents and Settings\hcooper.JOE\My Documents\Visual Studio
Projects\SystemNetDemo\TCPListenerForm.vb(140): Option Strict On disallows
implicit conversions from 'System.Net.Sockets.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.InvalidCastException' occured in
SystemNetDemo.exe
Additional information: Specified cast is not valid.
Any help here???

Hamil.

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

Imports System.Net.Sockets

Public Class MyTcpClient

Inherits TcpClient

Public IsConnected As Boolean

Public Sub New()
End Sub 'New

Public Sub UsingProtectedMethods()

'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.SuppressFinalize(Me)
End Sub 'UsingProtectedMethods

End Class

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

Imports System.IO
Imports System.net
Imports System.Net.Sockets
Imports System.Threading

Public Class TCPListenerForm
Inherits System.Windows.Forms.Form

Dim listening As Boolean
Dim localhostAddress 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.EventArgs) Handles btnStart.Click
btnStart.Enabled = False
btnStop.Enabled = True
Dim tr As New Thread(AddressOf ListenToClients)
tr.Start()
End Sub

Sub ListenToClients()
localhostAddress = IPAddress.Loopback
port = CInt(txtPort.Text)
tcpList = New TcpListener(localhostAddress, 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.AcceptTcpClient()
ns = tcpCli.GetStream
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.ToUpper
sw.WriteLine(returnedData)
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(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnStop.Click
btnStart.Enabled = True
btnStop.Enabled = False
listening = False
End Sub
End Class

Nov 21 '05 #1
1 4481
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.AcceptTcpClient()

gives this error during the pre compile phase.
C:\Documents and Settings\hcooper.JOE\My Documents\Visual Studio
Projects\SystemNetDemo\TCPListenerForm.vb(140): Option Strict On disallows
implicit conversions from 'System.Net.Sockets.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.InvalidCastException' occured in
SystemNetDemo.exe
Additional information: Specified cast is not valid.
Any help here???

Hamil.

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

Imports System.Net.Sockets

Public Class MyTcpClient

Inherits TcpClient

Public IsConnected As Boolean

Public Sub New()
End Sub 'New

Public Sub UsingProtectedMethods()

'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.SuppressFinalize(Me)
End Sub 'UsingProtectedMethods

End Class

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

Imports System.IO
Imports System.net
Imports System.Net.Sockets
Imports System.Threading

Public Class TCPListenerForm
Inherits System.Windows.Forms.Form

Dim listening As Boolean
Dim localhostAddress 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.EventArgs) Handles btnStart.Click
btnStart.Enabled = False
btnStop.Enabled = True
Dim tr As New Thread(AddressOf ListenToClients)
tr.Start()
End Sub

Sub ListenToClients()
localhostAddress = IPAddress.Loopback
port = CInt(txtPort.Text)
tcpList = New TcpListener(localhostAddress, 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.AcceptTcpClient()
ns = tcpCli.GetStream
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.ToUpper
sw.WriteLine(returnedData)
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(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnStop.Click
btnStart.Enabled = 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
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...
5
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...
1
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
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...
1
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...
3
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...
2
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...
5
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...
0
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...
3
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 3 Jan 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). For other local times, please check World Time Buddy In...
0
by: abbasky | last post by:
### Vandf component communication method one: data sharing ​ Vandf components can achieve data exchange through data sharing, state sharing, events, and other methods. Vandf's data exchange method...
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 7 Feb 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:30 (7.30PM). In this month's session, the creator of the excellent VBE...
0
by: fareedcanada | last post by:
Hello I am trying to split number on their count. suppose i have 121314151617 (12cnt) then number should be split like 12,13,14,15,16,17 and if 11314151617 (11cnt) then should be split like...
0
Git
by: egorbl4 | last post by:
Скачал я git, хотел начать настройку, а там вылезло вот это Что это? Что мне с этим делать? ...
1
by: davi5007 | last post by:
Hi, Basically, I am trying to automate a field named TraceabilityNo into a web page from an access form. I've got the serial held in the variable strSearchString. How can I get this into the...
0
by: MeoLessi9 | last post by:
I have VirtualBox installed on Windows 11 and now I would like to install Kali on a virtual machine. However, on the official website, I see two options: "Installer images" and "Virtual machines"....
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: Aftab Ahmad | last post by:
Hello Experts! I have written a code in MS Access for a cmd called "WhatsApp Message" to open WhatsApp using that very code but the problem is that it gives a popup message everytime I clicked on...

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.