Link to home
Start Free TrialLog in
Avatar of srcalc
srcalc

asked on

Creating TCPClient from Socket

I can't seem to modify the code from "101 VB .NET Samples - Advanced .NET Framework (Networking) - Use Sockets" from MSDN to allow the server program to accept a socket rather than a tcpclient. This is the important code:

    Private Sub DoListen()
        listener = New TcpListener(System.Net.IPAddress.Any, PORT_NUM)
        listener.Start()
        Do
            Dim client As New UserConnection(listener.AcceptTcpClient)
            AddHandler client.LineReceived, AddressOf OnLineReceived
            UpdateStatus("New connection found: waiting for log-in")
        Loop
    End Sub

I need to change it to something like this:

    Private Sub DoListen()
        listener = New TcpListener(System.Net.IPAddress.Any, PORT_NUM)
        listener.Start()
        Do
            Dim socket As Socket = listener.AcceptSocket
            Dim IPstr As String = CType(socket.RemoteEndPoint, System.Net.IPEndPoint).Address.ToString
            Dim tcp As New TcpClient(CType(socket.RemoteEndPoint, System.Net.IPEndPoint))
            Dim client As New UserConnection(tcp)
            AddHandler client.LineReceived, AddressOf OnLineReceived
            UpdateStatus("New connection found at IP" & IPstr & ": waiting for log-in")
        Loop
    End Sub

But this code doesn't work. Basically I need to code to this EE question:
https://www.experts-exchange.com/questions/21016007/Getting-IP-from-TCPClient.html

Thanks!
Avatar of drichards
drichards

You are creating a new unconnected TcpClient in this code.  That obviously is not what you intende.

If you want to use AcceptSocket, you will not be able to use TcpClient.  The best you can do is create a NetworkStream around the accepted socket.  There is no way to transfer a live connected socket to a new TcpClient.
You can cheat and use reflection to get (and set) the private members of an object if you really want.  See https://www.experts-exchange.com/questions/21070021/Reflection.html
Avatar of srcalc

ASKER

OK drcihards if you can give me some VB code that will work in my situation, the points go to you.
ASKER CERTIFIED SOLUTION
Avatar of gregoryyoung
gregoryyoung
Flag of Canada image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of srcalc

ASKER

That works perfectly gregoryyoung. Thanks!
although I believe its silly to have to do that :( .... i believe ms said they will be rectifying that.