473,396 Members | 1,725 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,396 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 4501
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...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
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...
0
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...

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.