Results 1 to 27 of 27

Thread: [RESOLVED] TCP client - server doubt on Atheist's example code

  1. #1

    Thread Starter
    Freelancer akhileshbc's Avatar
    Join Date
    Jun 2008
    Location
    Trivandrum, Kerala, India
    Posts
    7,652

    Resolved [RESOLVED] TCP client - server doubt on Atheist's example code

    Hi guys...

    I'm trying to the learn TCP client server communication.

    I have gone through Atheist's example code.

    But I'm having some doubt.
    What I'm trying to do is, the client will connect to the server and sends data. That's all. And the server will use this data for some other purpose.

    Here's the client code I have made:
    vb.net Code:
    1. Public Class frmMain
    2.     Private client As System.Net.Sockets.TcpClient
    3.  
    4.     Private Sub btnConnect_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnConnect.Click
    5.         '~~~ Checking if connection exists
    6.         If client.Connected = True Then
    7.             If MessageBox.Show("A connection already exists ! Do you want to terminate it and establish a new connection ?", "Connection exists !", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) = Windows.Forms.DialogResult.Yes Then
    8.                 client.Close()
    9.             Else
    10.                 Exit Sub
    11.             End If
    12.         End If
    13.  
    14.         Dim strServerIP As String = txtServerIP.Text
    15.         Dim intPort As Integer
    16.  
    17.         '~~~ Checking for valid inputs
    18.         If strServerIP.Length = 0 Then
    19.             MessageBox.Show("Please enter a valid IP address !", "IP address ?", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
    20.             txtServerIP.Focus()
    21.             Exit Sub
    22.         End If
    23.  
    24.         If Integer.TryParse(txtPort.Text, intPort) = False Then
    25.             MessageBox.Show("Please enter a valid port number !", "Port Number?", MessageBoxButtons.OK, MessageBoxIcon.Error)
    26.             txtPort.Focus()
    27.             Exit Sub
    28.         End If
    29.  
    30.         '~~~ Connecting
    31.         Try
    32.             client = New System.Net.Sockets.TcpClient(txtServerIP.Text, intPort)
    33.         Catch ex As Exception
    34.             MessageBox.Show(ex.Message)
    35.         End Try
    36.     End Sub
    37.  
    38.     '~~~ Sends a message to the server
    39.     Private Sub SendMessage(ByVal msg As String)
    40.         Dim sw As IO.StreamWriter
    41.         Try
    42.             sw = New IO.StreamWriter(client.GetStream)
    43.             sw.Write(msg)
    44.             sw.Flush()
    45.         Catch ex As Exception
    46.             MessageBox.Show(ex.ToString)
    47.         End Try
    48.     End Sub
    49.  
    50.     Private Sub frmMain_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
    51.         client.Close()
    52.     End Sub
    53.  
    54.     Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    55.         '~~~ Check if there's a connection or not
    56.         If client.Connected = False Then
    57.             MessageBox.Show("No connection exists ! Please connect to the server first !", "No connection to server", MessageBoxButtons.OK, MessageBoxIcon.Warning)
    58.             Exit Sub
    59.         End If
    60.         '~~~ Send the message to server
    61.         SendMessage("abc|123")
    62.     End Sub
    63. End Class
    But in the server side, I'm having confusion on the doRead and doListen events (of Athiest's code). Since, I'm not going to store the connected clients, I'm not going to use a class for the connected clients (in the server side).

    Can you please guide me on that part ?

    Thanks

    If my post was helpful to you, then express your gratitude using Rate this Post.
    And if your problem is SOLVED, then please Mark the Thread as RESOLVED (see it in action - video)
    My system: AMD FX 6100, Gigabyte Motherboard, 8 GB Crossair Vengance, Cooler Master 450W Thunder PSU, 1.4 TB HDD, 18.5" TFT(Wide), Antec V1 Cabinet

    Social Group: VBForums - Developers from India


    Skills: PHP, MySQL, jQuery, VB.Net, Photoshop, CodeIgniter, Bootstrap,...

  2. #2
    Raging swede Atheist's Avatar
    Join Date
    Aug 2005
    Location
    Sweden
    Posts
    8,018

    Re: TCP client - server doubt on Atheist's example code

    You need to keep a reference to the connected clients (at least their streams) in order to read from their NetworkStreams. Why do you not want to "store" the connected clients?
    Rate posts that helped you. I do not reply to PM's with coding questions.
    How to Get Your Questions Answered
    Current project: tunaOS
    Me on.. BitBucket, Google Code, Github (pretty empty)

  3. #3

    Thread Starter
    Freelancer akhileshbc's Avatar
    Join Date
    Jun 2008
    Location
    Trivandrum, Kerala, India
    Posts
    7,652

    Re: TCP client - server doubt on Atheist's example code

    Quote Originally Posted by Atheist View Post
    You need to keep a reference to the connected clients (at least their streams) in order to read from their NetworkStreams. Why do you not want to "store" the connected clients?
    Thanks for replying

    My intention was to accept the data received on the server and use it for some calculation and other things. And not keep tracking of the clients.

    So, I have to keep track of the clients inorder to work, right ?

    If my post was helpful to you, then express your gratitude using Rate this Post.
    And if your problem is SOLVED, then please Mark the Thread as RESOLVED (see it in action - video)
    My system: AMD FX 6100, Gigabyte Motherboard, 8 GB Crossair Vengance, Cooler Master 450W Thunder PSU, 1.4 TB HDD, 18.5" TFT(Wide), Antec V1 Cabinet

    Social Group: VBForums - Developers from India


    Skills: PHP, MySQL, jQuery, VB.Net, Photoshop, CodeIgniter, Bootstrap,...

  4. #4
    Raging swede Atheist's Avatar
    Join Date
    Aug 2005
    Location
    Sweden
    Posts
    8,018

    Re: TCP client - server doubt on Atheist's example code

    It sounds like you mean;
    Having a class containing the logic for each connected client = keeping track of clients.
    I would call it good design. However, do as you wish. There is no need to go with the class approach, just spawn a new thread when a client connects and read from the networkstream until its not needed anymore, then simply disconnect it.
    Rate posts that helped you. I do not reply to PM's with coding questions.
    How to Get Your Questions Answered
    Current project: tunaOS
    Me on.. BitBucket, Google Code, Github (pretty empty)

  5. #5

    Thread Starter
    Freelancer akhileshbc's Avatar
    Join Date
    Jun 2008
    Location
    Trivandrum, Kerala, India
    Posts
    7,652

    Re: TCP client - server doubt on Atheist's example code

    Quote Originally Posted by Atheist View Post
    It sounds like you mean;
    Having a class containing the logic for each connected client = keeping track of clients.
    I would call it good design. However, do as you wish. There is no need to go with the class approach, just spawn a new thread when a client connects and read from the networkstream until its not needed anymore, then simply disconnect it.
    Thanks

    My idea:
    Client will send data in the format :
    Code:
    [CONNECT]|field1|field2|field3|[CLOSE]
    So, the field1, field2 and field3 is the actual data send to the server.

    The idea of [CONNECT] and [CLOSE] was just for finding the start and end of the message.

    So, when the received data contains the [CLOSE] command, that connection is terminated.

    Am I going in the correct direction or making it a bit more complex ?

    If my post was helpful to you, then express your gratitude using Rate this Post.
    And if your problem is SOLVED, then please Mark the Thread as RESOLVED (see it in action - video)
    My system: AMD FX 6100, Gigabyte Motherboard, 8 GB Crossair Vengance, Cooler Master 450W Thunder PSU, 1.4 TB HDD, 18.5" TFT(Wide), Antec V1 Cabinet

    Social Group: VBForums - Developers from India


    Skills: PHP, MySQL, jQuery, VB.Net, Photoshop, CodeIgniter, Bootstrap,...

  6. #6
    Raging swede Atheist's Avatar
    Join Date
    Aug 2005
    Location
    Sweden
    Posts
    8,018

    Re: TCP client - server doubt on Atheist's example code

    So a client connects, sends 3 values like so:
    field1|field2|field3
    and then disconnects? Is this how it always will work?

    Then I do not see any need for the [connect] and [close] messages.
    Rate posts that helped you. I do not reply to PM's with coding questions.
    How to Get Your Questions Answered
    Current project: tunaOS
    Me on.. BitBucket, Google Code, Github (pretty empty)

  7. #7

    Thread Starter
    Freelancer akhileshbc's Avatar
    Join Date
    Jun 2008
    Location
    Trivandrum, Kerala, India
    Posts
    7,652

    Re: TCP client - server doubt on Atheist's example code

    Quote Originally Posted by Atheist View Post
    So a client connects, sends 3 values like so:
    field1|field2|field3
    and then disconnects? Is this how it always will work?

    Then I do not see any need for the [connect] and [close] messages.
    Yeah..!

    The client will always sends 3 values and it has no purpose of hearing what the server has to say about these values or anything like that.

    In simple, clients sends data. Server receives that data and saves it. No other information is passed back to the client. A one way approach.

    Thanks

    If my post was helpful to you, then express your gratitude using Rate this Post.
    And if your problem is SOLVED, then please Mark the Thread as RESOLVED (see it in action - video)
    My system: AMD FX 6100, Gigabyte Motherboard, 8 GB Crossair Vengance, Cooler Master 450W Thunder PSU, 1.4 TB HDD, 18.5" TFT(Wide), Antec V1 Cabinet

    Social Group: VBForums - Developers from India


    Skills: PHP, MySQL, jQuery, VB.Net, Photoshop, CodeIgniter, Bootstrap,...

  8. #8
    Raging swede Atheist's Avatar
    Join Date
    Aug 2005
    Location
    Sweden
    Posts
    8,018

    Re: TCP client - server doubt on Atheist's example code

    May I ask what these values are?
    Rate posts that helped you. I do not reply to PM's with coding questions.
    How to Get Your Questions Answered
    Current project: tunaOS
    Me on.. BitBucket, Google Code, Github (pretty empty)

  9. #9

    Thread Starter
    Freelancer akhileshbc's Avatar
    Join Date
    Jun 2008
    Location
    Trivandrum, Kerala, India
    Posts
    7,652

    Re: TCP client - server doubt on Atheist's example code

    Quote Originally Posted by Atheist View Post
    May I ask what these values are?
    an id, a value corresponding to that particular id, a message

    Example:
    1, 100, bad

    Last edited by akhileshbc; Feb 16th, 2011 at 07:57 AM. Reason: added example

    If my post was helpful to you, then express your gratitude using Rate this Post.
    And if your problem is SOLVED, then please Mark the Thread as RESOLVED (see it in action - video)
    My system: AMD FX 6100, Gigabyte Motherboard, 8 GB Crossair Vengance, Cooler Master 450W Thunder PSU, 1.4 TB HDD, 18.5" TFT(Wide), Antec V1 Cabinet

    Social Group: VBForums - Developers from India


    Skills: PHP, MySQL, jQuery, VB.Net, Photoshop, CodeIgniter, Bootstrap,...

  10. #10
    Raging swede Atheist's Avatar
    Join Date
    Aug 2005
    Location
    Sweden
    Posts
    8,018

    Re: TCP client - server doubt on Atheist's example code

    I would go with a binaryreader/writer approach.
    Each client would do something like so:
    Code:
    binaryWriter.Write(myByteValueID)
    binaryWriter.Write(mySecondByteValue)
    binaryWriter.Write(myStringMessage)
    And on the server side;
    Code:
    Dim id as Byte = binaryReader.ReadByte()
    Dim value as Byte = binaryReader.ReadByte()
    Dim message as String = binaryReader.ReadString()
    ' Disconnect client.
    This takes advantage of the fact that you know the size of the two first fields (I have assumed bytes here), which removes the need for delimiting tokens.

    My original code treated everything as strings which is not always the most elegant thing.
    Rate posts that helped you. I do not reply to PM's with coding questions.
    How to Get Your Questions Answered
    Current project: tunaOS
    Me on.. BitBucket, Google Code, Github (pretty empty)

  11. #11

    Thread Starter
    Freelancer akhileshbc's Avatar
    Join Date
    Jun 2008
    Location
    Trivandrum, Kerala, India
    Posts
    7,652

    Re: TCP client - server doubt on Atheist's example code

    Thanks

    That would be a good idea.

    I'm having confusion on the server side.
    Am I supposed to start reading the data just after accepting the connection ?

    Code:
    Private Sub doListen()
            Dim incomingClient As System.Net.Sockets.TcpClient
            Do
                incomingClient = listener.AcceptTcpClient 
                '~~~ here start reading the bytes
     
            Loop
        End Sub
    Am I correct ?

    If my post was helpful to you, then express your gratitude using Rate this Post.
    And if your problem is SOLVED, then please Mark the Thread as RESOLVED (see it in action - video)
    My system: AMD FX 6100, Gigabyte Motherboard, 8 GB Crossair Vengance, Cooler Master 450W Thunder PSU, 1.4 TB HDD, 18.5" TFT(Wide), Antec V1 Cabinet

    Social Group: VBForums - Developers from India


    Skills: PHP, MySQL, jQuery, VB.Net, Photoshop, CodeIgniter, Bootstrap,...

  12. #12
    Raging swede Atheist's Avatar
    Join Date
    Aug 2005
    Location
    Sweden
    Posts
    8,018

    Re: TCP client - server doubt on Atheist's example code

    Yes thats correct. Wether or not you choose to use multithreading at that point or not determines if your server will be able to accept multiple clients simultaneously or not.
    Rate posts that helped you. I do not reply to PM's with coding questions.
    How to Get Your Questions Answered
    Current project: tunaOS
    Me on.. BitBucket, Google Code, Github (pretty empty)

  13. #13

    Thread Starter
    Freelancer akhileshbc's Avatar
    Join Date
    Jun 2008
    Location
    Trivandrum, Kerala, India
    Posts
    7,652

    Re: TCP client - server doubt on Atheist's example code

    Quote Originally Posted by Atheist View Post
    Yes thats correct. Wether or not you choose to use multithreading at that point or not determines if your server will be able to accept multiple clients simultaneously or not.
    Thanks

    Here it goes...
    vb.net Code:
    1. Private Sub doListen()
    2.         Dim incomingClient As System.Net.Sockets.TcpClient
    3.         Do
    4.             incomingClient = listener.AcceptTcpClient 'Accept the incoming connection. This is a blocking method so execution will halt here until someone tries to connect.
    5.             Dim myBinReader As New BinaryReader(incomingClient.GetStream)
    6.             Dim i As Byte = myBinReader.ReadByte
    7.             Me.Text = i.ToString
    8.         Loop
    9.     End Sub
    I didn't tested the above code.

    Since it continuously loops, wouldn't it cause some issues ? I mean, even if a client is not connected, it would try to read the byte and process it !
    This line:
    Code:
    incomingClient = listener.AcceptTcpClient
    how can I make changes to the code, to avoid the continuous loop problem ?


    If my post was helpful to you, then express your gratitude using Rate this Post.
    And if your problem is SOLVED, then please Mark the Thread as RESOLVED (see it in action - video)
    My system: AMD FX 6100, Gigabyte Motherboard, 8 GB Crossair Vengance, Cooler Master 450W Thunder PSU, 1.4 TB HDD, 18.5" TFT(Wide), Antec V1 Cabinet

    Social Group: VBForums - Developers from India


    Skills: PHP, MySQL, jQuery, VB.Net, Photoshop, CodeIgniter, Bootstrap,...

  14. #14

    Thread Starter
    Freelancer akhileshbc's Avatar
    Join Date
    Jun 2008
    Location
    Trivandrum, Kerala, India
    Posts
    7,652

    Re: TCP client - server doubt on Atheist's example code

    Am I doing correct here:
    vb.net Code:
    1. Private Sub doListen()
    2.         Dim incomingClient As System.Net.Sockets.TcpClient
    3.         Do
    4.             incomingClient = listener.AcceptTcpClient 'Accept the incoming connection. This is a blocking method so execution will halt here until someone tries to connect.
    5.  
    6.             If incomingClient.Connected = True Then
    7.                 Dim myBinReader As New BinaryReader(incomingClient.GetStream)
    8.                 Dim i As Byte = myBinReader.ReadByte
    9.                 Me.Text = i.ToString
    10.             End If
    11.             incomingClient.Close()
    12.         Loop
    13.     End Sub

    Thanks

    If my post was helpful to you, then express your gratitude using Rate this Post.
    And if your problem is SOLVED, then please Mark the Thread as RESOLVED (see it in action - video)
    My system: AMD FX 6100, Gigabyte Motherboard, 8 GB Crossair Vengance, Cooler Master 450W Thunder PSU, 1.4 TB HDD, 18.5" TFT(Wide), Antec V1 Cabinet

    Social Group: VBForums - Developers from India


    Skills: PHP, MySQL, jQuery, VB.Net, Photoshop, CodeIgniter, Bootstrap,...

  15. #15
    Raging swede Atheist's Avatar
    Join Date
    Aug 2005
    Location
    Sweden
    Posts
    8,018

    Re: TCP client - server doubt on Atheist's example code

    AcceptTcpClient is a blocking call. It will return once a client has connected. Of course, there is no guarantee that the client IS still connected once it reaches the reading part of your code, but such is life with networking.
    Rate posts that helped you. I do not reply to PM's with coding questions.
    How to Get Your Questions Answered
    Current project: tunaOS
    Me on.. BitBucket, Google Code, Github (pretty empty)

  16. #16

    Thread Starter
    Freelancer akhileshbc's Avatar
    Join Date
    Jun 2008
    Location
    Trivandrum, Kerala, India
    Posts
    7,652

    Re: TCP client - server doubt on Atheist's example code

    Thanks a lot for clearing my doubts...

    Will play with the code and get in touch with you, if I have some doubts

    If my post was helpful to you, then express your gratitude using Rate this Post.
    And if your problem is SOLVED, then please Mark the Thread as RESOLVED (see it in action - video)
    My system: AMD FX 6100, Gigabyte Motherboard, 8 GB Crossair Vengance, Cooler Master 450W Thunder PSU, 1.4 TB HDD, 18.5" TFT(Wide), Antec V1 Cabinet

    Social Group: VBForums - Developers from India


    Skills: PHP, MySQL, jQuery, VB.Net, Photoshop, CodeIgniter, Bootstrap,...

  17. #17

    Thread Starter
    Freelancer akhileshbc's Avatar
    Join Date
    Jun 2008
    Location
    Trivandrum, Kerala, India
    Posts
    7,652

    Re: TCP client - server doubt on Atheist's example code

    Quote Originally Posted by Atheist View Post
    Of course, there is no guarantee that the client IS still connected once it reaches the reading part of your code, but such is life with networking.
    Another doubt, did you mean that creating a new sub doRead for reading from the client (just like you did in the example) will overcome this issue ?

    Or, it's good to continue using the one shot data reading with BinaryReader ?

    Thanks

    If my post was helpful to you, then express your gratitude using Rate this Post.
    And if your problem is SOLVED, then please Mark the Thread as RESOLVED (see it in action - video)
    My system: AMD FX 6100, Gigabyte Motherboard, 8 GB Crossair Vengance, Cooler Master 450W Thunder PSU, 1.4 TB HDD, 18.5" TFT(Wide), Antec V1 Cabinet

    Social Group: VBForums - Developers from India


    Skills: PHP, MySQL, jQuery, VB.Net, Photoshop, CodeIgniter, Bootstrap,...

  18. #18
    Raging swede Atheist's Avatar
    Join Date
    Aug 2005
    Location
    Sweden
    Posts
    8,018

    Re: TCP client - server doubt on Atheist's example code

    No that won't make any difference. You can continue with the approach you showed in your last code snippet.
    Rate posts that helped you. I do not reply to PM's with coding questions.
    How to Get Your Questions Answered
    Current project: tunaOS
    Me on.. BitBucket, Google Code, Github (pretty empty)

  19. #19

    Thread Starter
    Freelancer akhileshbc's Avatar
    Join Date
    Jun 2008
    Location
    Trivandrum, Kerala, India
    Posts
    7,652

    Re: TCP client - server doubt on Atheist's example code

    Quote Originally Posted by Atheist View Post
    No that won't make any difference. You can continue with the approach you showed in your last code snippet.
    Ok.. Thanks...

    Another question, I heard some people saying "be extremely cautious when opening ports". I'm confused !

    Are they pointing to the TCPListener's port (in the server side) ?
    How do we close it ?
    Or it is automatically closed when the listener is closed ?
    Code:
    objTCPListner.Stop()

    If my post was helpful to you, then express your gratitude using Rate this Post.
    And if your problem is SOLVED, then please Mark the Thread as RESOLVED (see it in action - video)
    My system: AMD FX 6100, Gigabyte Motherboard, 8 GB Crossair Vengance, Cooler Master 450W Thunder PSU, 1.4 TB HDD, 18.5" TFT(Wide), Antec V1 Cabinet

    Social Group: VBForums - Developers from India


    Skills: PHP, MySQL, jQuery, VB.Net, Photoshop, CodeIgniter, Bootstrap,...

  20. #20
    Raging swede Atheist's Avatar
    Join Date
    Aug 2005
    Location
    Sweden
    Posts
    8,018

    Re: TCP client - server doubt on Atheist's example code

    I would assume they mean opening ports in your router.
    Are you familiar with the concept of Network Address Translation (NAT)?
    Rate posts that helped you. I do not reply to PM's with coding questions.
    How to Get Your Questions Answered
    Current project: tunaOS
    Me on.. BitBucket, Google Code, Github (pretty empty)

  21. #21

    Thread Starter
    Freelancer akhileshbc's Avatar
    Join Date
    Jun 2008
    Location
    Trivandrum, Kerala, India
    Posts
    7,652

    Re: TCP client - server doubt on Atheist's example code

    Quote Originally Posted by Atheist View Post
    Are you familiar with the concept of Network Address Translation (NAT)?
    No.. I haven't heard about that yet.

    So, there's no need to worry about the "opening of ports" right ?

    Thanks

    If my post was helpful to you, then express your gratitude using Rate this Post.
    And if your problem is SOLVED, then please Mark the Thread as RESOLVED (see it in action - video)
    My system: AMD FX 6100, Gigabyte Motherboard, 8 GB Crossair Vengance, Cooler Master 450W Thunder PSU, 1.4 TB HDD, 18.5" TFT(Wide), Antec V1 Cabinet

    Social Group: VBForums - Developers from India


    Skills: PHP, MySQL, jQuery, VB.Net, Photoshop, CodeIgniter, Bootstrap,...

  22. #22
    Raging swede Atheist's Avatar
    Join Date
    Aug 2005
    Location
    Sweden
    Posts
    8,018

    Re: TCP client - server doubt on Atheist's example code

    When you call Listen on your TcpListener, you will immediately begin listening to your local port X (if your PC firewall doesnt block it). Other computers on your local network can connect to your computer by your local IP and port X.
    The problem arises when a computer outside of your local network wants to connect. It is not possible for this outside computer to connect to your local IP for obvious reasons, so it must use your external IP. When the router receives the connection request from this outside computer it does not know what to do with it. Which computer inside your local network is this connection request directed to? This is where port forwarding ("opening" ports) come in.
    You forward port Y on your router to your local IP and port X to make it accessible from outside hosts. This is what is considered "dangerous". Anyone could attempt to connect to your external IP on port Y.
    Software that is poorly written might present security issues if a malicious client connects.
    Rate posts that helped you. I do not reply to PM's with coding questions.
    How to Get Your Questions Answered
    Current project: tunaOS
    Me on.. BitBucket, Google Code, Github (pretty empty)

  23. #23

    Thread Starter
    Freelancer akhileshbc's Avatar
    Join Date
    Jun 2008
    Location
    Trivandrum, Kerala, India
    Posts
    7,652

    Re: TCP client - server doubt on Atheist's example code

    Quote Originally Posted by Atheist View Post
    When the router receives the connection request from this outside computer it does not know what to do with it. Which computer inside your local network is this connection request directed to? This is where port forwarding ("opening" ports) come in.
    You forward port Y on your router to your local IP and port X to make it accessible from outside hosts. This is what is considered "dangerous". Anyone could attempt to connect to your external IP on port Y.
    Software that is poorly written might present security issues if a malicious client connects.
    Thanks for explaining...

    Is this port forwarding facility done implicitly when we start the listening or it has to be done explicitly ?
    My development PC is connected to a cable modem.

    If my post was helpful to you, then express your gratitude using Rate this Post.
    And if your problem is SOLVED, then please Mark the Thread as RESOLVED (see it in action - video)
    My system: AMD FX 6100, Gigabyte Motherboard, 8 GB Crossair Vengance, Cooler Master 450W Thunder PSU, 1.4 TB HDD, 18.5" TFT(Wide), Antec V1 Cabinet

    Social Group: VBForums - Developers from India


    Skills: PHP, MySQL, jQuery, VB.Net, Photoshop, CodeIgniter, Bootstrap,...

  24. #24
    Raging swede Atheist's Avatar
    Join Date
    Aug 2005
    Location
    Sweden
    Posts
    8,018

    Re: TCP client - server doubt on Atheist's example code

    It is done explicitly.
    So you are not behind a router? In that case - no need to forward any ports.
    Rate posts that helped you. I do not reply to PM's with coding questions.
    How to Get Your Questions Answered
    Current project: tunaOS
    Me on.. BitBucket, Google Code, Github (pretty empty)

  25. #25

    Thread Starter
    Freelancer akhileshbc's Avatar
    Join Date
    Jun 2008
    Location
    Trivandrum, Kerala, India
    Posts
    7,652

    Re: TCP client - server doubt on Atheist's example code

    Quote Originally Posted by Atheist View Post
    It is done explicitly.
    So you are not behind a router? In that case - no need to forward any ports.
    Thanks...

    I did some testing and everything works fine..

    Here's the code for server. Any improvements needed in the closing or disposing parts ?

    Server:
    vb.net Code:
    1. '~~~ This sub will work in a background thread
    2.     Private Sub doListen()
    3.         Dim incomingClient As System.Net.Sockets.TcpClient
    4.  
    5.         Dim myBinReader As BinaryReader
    6.  
    7.         Dim bytHValue As Byte
    8.         Dim strPid As String
    9.  
    10.         Do
    11.             Try
    12.                 incomingClient = listener.AcceptTcpClient 'Accept the incoming connection. This is a blocking method so execution will halt here until someone tries to connect.
    13.  
    14.                 myBinReader = New BinaryReader(incomingClient.GetStream)
    15.                 bytHValue = myBinReader.ReadByte
    16.                 strPid = myBinReader.ReadString
    17.                 myBinReader.Close()
    18.  
    19.                 '~~~ Pass the messages from client for further processing
    20.                 MessageFromClient(bytHValue.ToString, strPid)
    21.  
    22.             Catch ex As Exception
    23.                 MessageBox.Show(ex.Message)
    24.             End Try
    25.         Loop
    26.     End Sub
    27.  
    28. '..........
    29.  
    30. '~~~ start
    31.     Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    32.         listener = New System.Net.Sockets.TcpListener(System.Net.IPAddress.Any, 43001) 'The TcpListener will listen for incoming connections at port 43001
    33.         listener.Start() 'Start listening.
    34.         listenThread = New System.Threading.Thread(AddressOf doListen) 'This thread will run the doListen method
    35.         listenThread.IsBackground = True 'Since we dont want this thread to keep on running after the application closes, we set isBackground to true.
    36.         listenThread.Start() 'Start executing doListen on the worker thread.
    37.     End Sub
    38. '~~~ stop
    39.     Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
    40.         listenThread.Abort()
    41.         listener.Stop()
    42.     End Sub

    Client:
    vb.net Code:
    1. Public Class frmMain
    2.     Private client As New System.Net.Sockets.TcpClient
    3.  
    4.     Dim strServerIP As String
    5.     Dim intPort As Integer
    6.  
    7.     Private Sub btnConnect_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnConnect.Click
    8.  
    9.         strServerIP = txtServerIP.Text
    10.  
    11.         '~~~ Checking for valid inputs
    12.         If strServerIP.Length = 0 Then
    13.             MessageBox.Show("Please enter a valid IP address !", "IP address ?", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
    14.             txtServerIP.Focus()
    15.             Exit Sub
    16.         End If
    17.  
    18.         If Integer.TryParse(txtPort.Text, intPort) = False Then
    19.             MessageBox.Show("Please enter a valid port number !", "Port Number?", MessageBoxButtons.OK, MessageBoxIcon.Error)
    20.             txtPort.Focus()
    21.             Exit Sub
    22.         End If
    23.  
    24.         '~~~ Connecting
    25.         Try
    26.             'client = New System.Net.Sockets.TcpClient(txtServerIP.Text, intPort)
    27.             client.Connect(txtServerIP.Text, intPort)
    28.             MessageBox.Show("Connected!")
    29.         Catch ex As Exception
    30.             MessageBox.Show(ex.Message, "Connection problem", MessageBoxButtons.OK, MessageBoxIcon.Error)
    31.         End Try
    32.     End Sub
    33.  
    34.     '~~~ Sends a message to the server
    35.     Private Sub SendMessage(ByVal msg As String)
    36.         Try
    37.             If client.Connected = False Then
    38.                 client.Connect(strServerIP, intPort)
    39.             End If
    40.         Catch ex As Exception
    41.             MessageBox.Show(ex.Message & vbNewLine & vbNewLine & "Try re-entering the IP address and port. Then connect to the server again.", "Connection Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
    42.         End Try
    43.  
    44.         Try
    45.             '~~~ Send the message to server
    46.             Dim myBinWriter As New System.IO.BinaryWriter(client.GetStream)
    47.             myBinWriter.Write(CByte(123)) '~~~ example
    48.             myBinWriter.Write("123456")   '~~~ example
    49.             myBinWriter.Close()
    50.         Catch ex As Exception
    51.             MessageBox.Show(ex.ToString, "Error on sending data", MessageBoxButtons.OK, MessageBoxIcon.Error)
    52.         End Try
    53.     End Sub
    54.  
    55.     Private Sub frmMain_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
    56.         client.Close()
    57.     End Sub
    58. End Class

    Thanks

    If my post was helpful to you, then express your gratitude using Rate this Post.
    And if your problem is SOLVED, then please Mark the Thread as RESOLVED (see it in action - video)
    My system: AMD FX 6100, Gigabyte Motherboard, 8 GB Crossair Vengance, Cooler Master 450W Thunder PSU, 1.4 TB HDD, 18.5" TFT(Wide), Antec V1 Cabinet

    Social Group: VBForums - Developers from India


    Skills: PHP, MySQL, jQuery, VB.Net, Photoshop, CodeIgniter, Bootstrap,...

  26. #26
    Raging swede Atheist's Avatar
    Join Date
    Aug 2005
    Location
    Sweden
    Posts
    8,018

    Re: TCP client - server doubt on Atheist's example code

    That looks alright as far as I can see!
    Rate posts that helped you. I do not reply to PM's with coding questions.
    How to Get Your Questions Answered
    Current project: tunaOS
    Me on.. BitBucket, Google Code, Github (pretty empty)

  27. #27

    Thread Starter
    Freelancer akhileshbc's Avatar
    Join Date
    Jun 2008
    Location
    Trivandrum, Kerala, India
    Posts
    7,652

    Re: TCP client - server doubt on Atheist's example code

    Quote Originally Posted by Atheist View Post
    That looks alright as far as I can see!
    Ok.. Thanks...

    If my post was helpful to you, then express your gratitude using Rate this Post.
    And if your problem is SOLVED, then please Mark the Thread as RESOLVED (see it in action - video)
    My system: AMD FX 6100, Gigabyte Motherboard, 8 GB Crossair Vengance, Cooler Master 450W Thunder PSU, 1.4 TB HDD, 18.5" TFT(Wide), Antec V1 Cabinet

    Social Group: VBForums - Developers from India


    Skills: PHP, MySQL, jQuery, VB.Net, Photoshop, CodeIgniter, Bootstrap,...

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width