Error using tcpclient/tcplistener
I'm trying to run a sample tcpclient/ tcpListener program written in VB.NET on VS 2003 (.net framework 1.1).
When I run this console program, I get 2 errors - 1) The requested address is not valid in its context - at System.Net.Sockets.Socket.Bind(EndPoint localEP)
2) System.InvalidOperationException : Not listening. Please call the Start() method - at System.Net.Sockets.TcpListener.AcceptTcpClient()
The code as follows:
TCPListener -
Imports
System.Net.SocketsImports
System.TextClass
TCPSrvSharedSub Main()Console.ReadLine()
Const portNumberAsInteger = 1526Dim addrIPAs System.Net.IPAddress = System.Net.IPAddress.Parse("170.186.144.132")Dim tcpListenerAs TcpListenerTrytcpListener =
New TcpListener(addrIP, portNumber)tcpListener.Start()
Console.WriteLine("Waiting for connection...")
Catch exAs SocketExceptionConsole.WriteLine(ex.ToString())
EndTryTryDim tcpClientAs TcpClient = tcpListener.AcceptTcpClient()tcpListener.Start()
Console.WriteLine("Connection accepted.")
Console.ReadLine()
' Get the streamDim networkStreamAs NetworkStream = tcpClient.GetStream()' Read the stream into a byte arrayDim bytes(tcpClient.ReceiveBufferSize)AsBytenetworkStream.Read(bytes, 0,
CInt(tcpClient.ReceiveBufferSize))' Return the data received from the client to the console.Dim clientdataAsString = Encoding.ASCII.GetString(bytes)Console.WriteLine(("Client sent: " + clientdata))
Console.ReadLine()
Dim responseStringAsString = "Connected to server."Dim sendBytesAs [Byte]() = Encoding.ASCII.GetBytes(responseString)networkStream.Write(sendBytes, 0, sendBytes.Length)
Console.WriteLine(("Message Sent /> : " + responseString))
Console.ReadLine()
'Close TcpListener and TcpClient.tcpClient.Close()
tcpListener.Stop()
Console.WriteLine("exit")
Console.ReadLine()
Catch eAs ExceptionConsole.WriteLine(e.ToString())
Console.ReadLine()
EndTryEndSubEnd
ClassTCPClient part-
Imports
System.Net.SocketsImports
System.TextClass
TCPCliSharedSub Main()Console.ReadLine()
Dim tcpClientAsNew System.Net.Sockets.TcpClientDim addrIPAs System.Net.IPAddress = System.Net.IPAddress.Parse("170.186.144.132")tcpClient.Connect(addrIP, 1526)
Dim networkStreamAs NetworkStream = tcpClient.GetStream()If networkStream.CanWriteAnd networkStream.CanReadThen' Do a simple write.Dim sendBytesAs [Byte]() = Encoding.ASCII.GetBytes("Is anybody there")networkStream.Write(sendBytes, 0, sendBytes.Length)
' Read the NetworkStream into a byte buffer.Dim bytes(tcpClient.ReceiveBufferSize)AsBytenetworkStream.Read(bytes, 0,
CInt(tcpClient.ReceiveBufferSize))' Output the data received from the host to the console.Dim returndataAsString = Encoding.ASCII.GetString(bytes)Console.WriteLine(("Host returned: " + returndata))
Console.ReadLine()
ElseIfNot networkStream.CanReadThenConsole.WriteLine("cannot not write data to this stream")
Console.ReadLine()
tcpClient.Close()
ElseIfNot networkStream.CanWriteThenConsole.WriteLine("cannot read data from this stream")
Console.ReadLine()
tcpClient.Close()
EndIfEndIfEndIf' pause so user can view the console outputConsole.ReadLine()
EndSubEnd
Class
[9156 byte] By [
Krutika] at [2007-12-23]
You're starting the TcpListener twice. You start the listener, accept the TcpClient and then start the listener again.. Remove the second one here:
Dim tcpClient As TcpClient = tcpListener.AcceptTcpClient()
tcpListener.Start()
Mariya
I removed the second Start(), but still the error 1 stay: The requested address is not valid in its context.
I'm able to telnet the mainframe successfully. help please..
Hello Kruthika , '
The above issue may happen if you are using the TCP command socket layer is corrupt or some of the access is blocked , try to login to the windows as an administrator and check if the issue happens , if you still have any issues , please send a screenshot to me
My E-mail address is mgunjal@gmail.com
Thanks and Regards
Manoj Gunjal
Service and support Excecutive
McAfee Antivirus Corporation
I may not be able to log in as administrator, is there any other way?
Manoj: I tried emailing you the program and snapshot of error
What line is throwing the bind error? What exactly is the exception and stack trace?
I disabled the antivirus until my testing was complete.
If I use a tcpclient the error is gone, but if I try to use a socket as
Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
then I get the error :
The target machine actively refused the connection at the bind method.
I had a few more questions about using tcpClient instead of winsock.
I'm migrating VB6 socket functions to equivalent VB.NET tcp client/server functions.
I'm using VS 2003 and .NET Framework 1.1 and I had the following questions:
1) Is socket.WSAStartup used in tcpClient?
2) To create a socket socket.socket and socket.connect were used. Does tcpClient.Connect replace these two functions?
3)For LingerTime, socket.setsockopt was used in winsock. Is tcpClient.LingerState.LingerTime the Tcp equivalent?
4) Is socket.bind required in tcpClient? If so, is there any equivalent in TCP?
5) To check if there are any connections waiting, is tcpClient.Pending is used?
6) To replace socket.Listen using TCPClient, should the tcpClient be just srated using tcpClient.Start?
7) For socket.accept, the TcpClient equivalent is tcpClient.AcceptTcpClient?
8) For socket.send, the TcpClient equivalent is tcpClient.Write?
9) For socket.recv, the TcpClient equivalent is tcpClient.Read?
10) Instead of socket.closesocket and socket.WSACleanup, is tcpclient.Close used?
11) Is there a tcpClient equivalent of socket.getsockname?
12) How to check if the tcpclient buffer is clear or not ?
Where exactly are you using the socket?If you're using Socket class to connect to TcpListener you have to change the TcpListener to use AcceptSocket instead of AcceptTcpClient. Does this answer your question? Basically TcpClient is designed in such a way to make connecting very easy. If you need greater flexibility than the TcpClient offers then use the Socket calss.
I've noticed you are mixing the terms client and server.
1) Is socket.WSAStartup used in tcpClient?
TcpClient creates a socket to send and receive data and abstracts you from most of the details. You don't have to call WSAStartup.
2) To create a socket socket.socket and socket.connect were used. Does tcpClient.Connect replace these two functions?
Yes
3)For LingerTime, socket.setsockopt was used in winsock. Is tcpClient.LingerState.LingerTime the Tcp equivalent?
yes
4) Is socket.bind required in TcpClient? If so, is there any equivalent in TCP?
no, you don't have to bind explicitly
5) To check if there are any connections waiting, is tcpClient.Pending is used?
There is no TcpClient.Pending. You can get or set the uderlying socket using the client property;
6) To replace socket.Listen using TCPClient, should the tcpClient be just srated using tcpClient.Start?
there is no TcpClient.Start.
You either use Connect or one of the overloaded constructors to establish the connection and that's it
Dim tcpClient As New TcpClient
Dim ipAddress As IPAddress = Dns.GetHostEntry("www.contoso.com").AddressList(0)
Dim ipEndPoint As New IPEndPoint(ipAddress, 11004)
tcpClient.Connect(ipEndPoint)
or
Dim localEP As IPEndPoint
Dim instance As New TcpClient(localEP)
7) For socket.accept, the TcpClient equivalent is tcpClient.AcceptTcpClient?
Either TcpListener.AcceptTcpClient or TcpListener.AcceptSocket
...
Once again - tcp client is not so flexible, it was meant to be easy to use. If you want you can always get/set the underlying socket it creates. For example, let's say you want to change the buffer size.
Dim client As New TcpClient()
Dim s As Socket = client.Client
If Not s.Connected Then
s.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer, 16384)
Console.WriteLine("client is not connected, ReceiveBuffer set" + ControlChars.Lf)
Else
Console.WriteLine("client is connected")
You should carefully read the documantation and the samples on the web:
http://msdn2.microsoft.com/en-us/library/system.net.sockets.tcpclient.aspx
http://msdn2.microsoft.com/en-us/library/zsyxy9k2.aspx
Mariya
Thank you for answering my queries.
The vb application was using winsock ot connect ot tcp. After migrating this application vb 6 to vb.net, I need to change the implementation to access tcp. Hence using tcpclient in api.
I have 3 more questions:
1) What does the function WSASelect() do?
2) How to check if the tcpclient buffer is clear or not ?
3) Is there a tcpClient equivalent of socket.getsockname?
You should really to to http://msdn2.microsoft.com and search for those functions
1. Given a list of socket descriptors WSASelect() chooses which socket has data for you and gives it back to you
2 and 3: You don't need to do it yourself; you just create a tcp client and do connect and that's it. Try the samples from my previous post
Mariya
The error cleared, but I'm unable to get any info from server.
Hence retracing the errors.
Code:
Const
portNumber As Integer = 1526 Dim addrIP As System.Net.IPAddress = System.Net.IPAddress.Parse("110.186.216.38")
Dim tcpListener As TcpListener
Try
tcpListener =
New TcpListener(addrIP, portNumber)tcpListener.Start()
Console.WriteLine("Waiting for connection...")
Catch ex As ExceptionMsgBox(ex.StackTrace.ToString)
End TryStackTrace:
at System.Net.Sockets.Socket.Bind(EndPoint locapEP)
at System.Net.Sockets.TcpListener.Start()
Do I need to make changes on the server part to receive message back to client?
Is there anyother way to check if the server is receiving messages from client?
Please advise
I don't understand why you'd like to reintroduce the errors? You'll just get the error message
The TCPListener Sample I pointed you to echoes the messages it receives from the client and prints them out on the console. You can modify it to write to a log file instead or the server can reply to the client with "received " + some message...
Mariya
Hi Mariya,
I'm reintroducing the error as I'm getting a new error which goes like this:
System.IO.IOException: Unable to read data from the transport connection
System.Net.Sockets.SocketsException: An established connection was aborted by the software in your host machine
I need help claering these errors
This last error sounds like the firewall (or antivirus software) blocking your connections
Mariya,
I just came across your post and was wondering if you have you solved your problem. If not, I was wondering if I could help.
Mike