[RESOLVED] [2008] Can I add a TCPClient Component-VBForums
Page 1 of 5 1234 ... LastLast
Results 1 to 40 of 163

Thread: [RESOLVED] [2008] Can I add a TCPClient Component

  1. #1

    Thread Starter
    Addicted Member
    Join Date
    Dec 2007
    Posts
    167

    Resolved [RESOLVED] [2008] Can I add a TCPClient Component

    Im learning Tcp communication right now, and Im a newbie :P
    First can i add a component to the form for tcpclient and tcpserver like a add one for a textbox and a botton?

    Second, which method is better
    Dim listener As Net.Sockets.TcpListener
    Dim listenThread As Threading.Thread

    or Dim tcpClient As New System.Net.Sockets.TcpClient()

    what should i use?

  2. #2
    Member
    Join Date
    Nov 2007
    Posts
    47

    Re: [2008] Can I add a TCPClient Component

    It matters what you are trying to accomplish with your program. Do you want the listener on a different thread?

    "First can i add a component to the form for tcpclient and tcpserver like a add one for a textbox and a botton?"

    Do you mean drag and drop?

  3. #3

    Thread Starter
    Addicted Member
    Join Date
    Dec 2007
    Posts
    167

    Re: [2008] Can I add a TCPClient Component

    yes i mean drag and drop
    and what i want to do is 2 simple programs that send strings to each others.

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

    Re: [2008] Can I add a TCPClient Component

    The TcpClient is not a control that can be dragged onto the form, its a class of which you create an instance at runtime and use however you want.
    ---My Flickr photo (mostly screenshots these days!) stream. Have a look!

    Rate posts that helped you. I do not reply to PM's with coding questions.
    How to Get Your Questions Answered
    TCP client/server connection | Retrieving the EventHandler for any Event by code.
    Me on.. BitBucket, Google Code, Github (pretty empty)

  5. #5

    Thread Starter
    Addicted Member
    Join Date
    Dec 2007
    Posts
    167

    Re: [2008] Can I add a TCPClient Component

    ok, now can somone give me the simplest example possible :P
    Please
    Client:
    How To connect
    Send Data
    Recieve Data

    Server:
    How To listen
    Send Data
    Receive Data

    Ive searched the form and google, but Im not understanding the code :S
    I need something very simple

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

    Re: [2008] Can I add a TCPClient Component

    There are so many examples all over this forum, it shouldnt be needed to create yet another one.
    ---My Flickr photo (mostly screenshots these days!) stream. Have a look!

    Rate posts that helped you. I do not reply to PM's with coding questions.
    How to Get Your Questions Answered
    TCP client/server connection | Retrieving the EventHandler for any Event by code.
    Me on.. BitBucket, Google Code, Github (pretty empty)

  7. #7
    .NUT jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    87,850

    Re: [2008] Can I add a TCPClient Component

    The MSDN Library documentation contains examples too. Have you read the documentation?

    Note that a class must inherit, either directly or indirectly, the System.ComponentModel.Component class in order to be created in the designer. The System.Windows.Forms.Control class inherits Component, so all controls can be added in the designer. If you ever want to know whether a class can be created in the designer in future you don't need to ask. Simply open its MSDN documentation and check its ancestry for the Component class.

    2007-2014

    Why is my data not saved to my database? | MSDN Data Walkthroughs
    MSDN "How Do I?" Videos: VB | C#
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts) | WP8 Turnstile Feather Transition with Pivot Control
    Beginner Tutorials: VB | C# | SQL

  8. #8

    Thread Starter
    Addicted Member
    Join Date
    Dec 2007
    Posts
    167

    Re: [2008] Can I add a TCPClient Component

    so I will follow Atheist's example since it looks pretty simple

    The client side would be then
    Code:
    Dim listener As Net.Sockets.TcpListener    Dim listenThread As Threading.Thread    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load        listener = New Net.Sockets.TcpListener("127.0.0.1", 32111)        listener.Start()        listenThread = New Threading.Thread(AddressOf DoListen)        listenThread.IsBackground = True        listenThread.Start()    End Sub
    The Server side would be
    Code:
    Dim listener As Net.Sockets.TcpListener
    Private Sub DoListen()        'This is the sub that does all the actual "listening". Its an endless loop that calls the AcceptTcpClient method over and over.        'If there is no connecting TcpClient, it will raise an exception but we will ignore this by catching it in a try statement and doing nothing with it.        'On the other hand, If a client has connected, it proceeds to the next line and a streamreader reads the incoming stream and shows it in a messagebox.        Dim sr As IO.StreamReader        Do            Try                Dim client As Net.Sockets.TcpClient = listener.AcceptTcpClient                sr = New IO.StreamReader(client.GetStream)                MessageBox.Show(sr.ReadToEnd)                sr.Close()            Catch            End Try        Loop    End Sub
    right?
    this will only connect the two programs?
    how to send information after connection?

  9. #9
    Frenzied Member
    Join Date
    Mar 2006
    Location
    Pennsylvania
    Posts
    1,069

    Re: [2008] Can I add a TCPClient Component

    Did you look at msdn's 101 code examples? The Sockets example shows you how to do all of this, including sending messages back and forth, in a simplistic manner.

  10. #10
    Lively Member
    Join Date
    May 2007
    Posts
    87

    Re: [2008] Can I add a TCPClient Component

    Try winsocket.

    http://www.vwsoftwaresolutions.nl/winsock2005.dll.zip

    Its much easier to use when you dont know anything about networking(programming) and if you would understand you should write something like this on your own anyway.

    Gl with it

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

    Re: [2008] Can I add a TCPClient Component

    Quote Originally Posted by ovanwijk
    Try winsocket.

    http://www.vwsoftwaresolutions.nl/winsock2005.dll.zip

    Its much easier to use when you dont know anything about networking(programming) and if you would understand you should write something like this on your own anyway.

    Gl with it
    Yes he could use this, but since he said he was learning TCP communications i highly suggest learning how to use the classes in the System.Net.Socket namespace, because:
    1. They provide much more functionallity and flexibility.
    2. If you dont learn the basics of Tcp communications in .Net and begin using a component like this, as soon as you want to make the slightest change in how the Winsock component works, you're gonna get stuck.
    ---My Flickr photo (mostly screenshots these days!) stream. Have a look!

    Rate posts that helped you. I do not reply to PM's with coding questions.
    How to Get Your Questions Answered
    TCP client/server connection | Retrieving the EventHandler for any Event by code.
    Me on.. BitBucket, Google Code, Github (pretty empty)

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

    Re: [2008] Can I add a TCPClient Component

    Quote Originally Posted by perito
    so I will follow Atheist's example since it looks pretty simple

    The client side would be then
    Code:
    Dim listener As Net.Sockets.TcpListener    Dim listenThread As Threading.Thread    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load        listener = New Net.Sockets.TcpListener("127.0.0.1", 32111)        listener.Start()        listenThread = New Threading.Thread(AddressOf DoListen)        listenThread.IsBackground = True        listenThread.Start()    End Sub
    The Server side would be
    Code:
    Dim listener As Net.Sockets.TcpListener
    Private Sub DoListen()        'This is the sub that does all the actual "listening". Its an endless loop that calls the AcceptTcpClient method over and over.        'If there is no connecting TcpClient, it will raise an exception but we will ignore this by catching it in a try statement and doing nothing with it.        'On the other hand, If a client has connected, it proceeds to the next line and a streamreader reads the incoming stream and shows it in a messagebox.        Dim sr As IO.StreamReader        Do            Try                Dim client As Net.Sockets.TcpClient = listener.AcceptTcpClient                sr = New IO.StreamReader(client.GetStream)                MessageBox.Show(sr.ReadToEnd)                sr.Close()            Catch            End Try        Loop    End Sub
    right?
    this will only connect the two programs?
    how to send information after connection?
    My example was very basic and needs some adjustment to be more effective. But basically the server side should have a TcpListener listening on a specified port and the client side should have a TcpClient connecting to the server on the same port.
    ---My Flickr photo (mostly screenshots these days!) stream. Have a look!

    Rate posts that helped you. I do not reply to PM's with coding questions.
    How to Get Your Questions Answered
    TCP client/server connection | Retrieving the EventHandler for any Event by code.
    Me on.. BitBucket, Google Code, Github (pretty empty)

  13. #13

    Thread Starter
    Addicted Member
    Join Date
    Dec 2007
    Posts
    167

    Re: [2008] Can I add a TCPClient Component

    i dont need it to be more effective. im still trying to make my client and server connect!!
    so the code u provide is only for the server not the client... ? right?
    im not understanding the code... is it for 2 programs or is it only for the server?

    if its only for the server, could you PLEASE show me how a client would connect..

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

    Re: [2008] Can I add a TCPClient Component

    Quote Originally Posted by perito
    i dont need it to be more effective. im still trying to make my client and server connect!!
    so the code u provide is only for the server not the client... ? right?
    im not understanding the code... is it for 2 programs or is it only for the server?

    if its only for the server, could you PLEASE show me how a client would connect..
    In the specific post by me that you linked too, there is only code for the server side. But in the same thread, I've got examples for the client side aswell.
    Anyway, I'll create one more example..

    Server side:
    Form:
    VB.Net Code:
    1. Public Class Form1
    2.     Private listener As System.Net.Sockets.TcpListener
    3.     Private listenThread As System.Threading.Thread
    4.  
    5.     Private clients As New List(Of ConnectedClient) 'This list will store all connected clients.
    6.  
    7.     Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    8.         listener = New System.Net.Sockets.TcpListener(System.Net.IPAddress.Any, 43001) 'The TcpListener will listen for incoming connections at port 43001
    9.         listener.Start() 'Start listening.
    10.         listenThread = New System.Threading.Thread(AddressOf doListen) 'This thread will run the doListen method
    11.         listenThread.IsBackground = True 'Since we dont want this thread to keep on running after the application closes, we set isBackground to true.
    12.         listenThread.Start() 'Start executing doListen on the worker thread.
    13.     End Sub
    14.  
    15.     Private Sub doListen()
    16.         Dim incomingClient As System.Net.Sockets.TcpClient
    17.         Do
    18.             incomingClient = listener.AcceptTcpClient 'Accept the incoming connection. This is a blocking method so execution will halt here until someone tries to connect.
    19.             Dim connClient As New ConnectedClient(incomingClient, Me) 'Create a new instance of ConnectedClient (check its constructor to see whats happening now).
    20.             AddHandler connClient.dataReceived, AddressOf Me.messageReceived
    21.             clients.Add(connClient) 'Adds the connected client to the list of connected clients.
    22.  
    23.         Loop
    24.     End Sub
    25.  
    26.     Public Sub removeClient(ByVal client As ConnectedClient)
    27.         If clients.Contains(client) Then
    28.             clients.Remove(client)
    29.         End If
    30.     End Sub
    31.  
    32.     Private Sub messageReceived(ByVal sender As ConnectedClient, ByVal message As String)
    33.         'A message has been received from one of the clients.
    34.         'To determine who its from, use the sender object.
    35.         'sender.SendMessage can be used to reply to the sender.
    36.  
    37.         Dim data() As String = message.Split("|"c) 'Split the message on each | and place in the string array.
    38.         Select Case data(0)
    39.             Case "CONNECT"
    40.                 'We use GetClientByName to make sure no one else is using this username.
    41.                 'It will return Nothing if the username is free.
    42.                 'Since the client sent the message in this format: CONNECT|UserName, the username will be in the array on index 1.
    43.                 If GetClientByName(data(1)) Is Nothing Then
    44.                     'The username is not taken, we can safely assign it to the sender.
    45.                     sender.Username = data(1)
    46.                 End If
    47.             Case "DISCONNECT"
    48.                 removeClient(sender)
    49.         End Select
    50.  
    51.     End Sub
    52.  
    53.     Private Function GetClientByName(ByVal name As String) As ConnectedClient
    54.         For Each cc As ConnectedClient In clients
    55.             If cc.Username = name Then
    56.                 Return cc 'client found, return it.
    57.             End If
    58.         Next
    59.         'If we've reached this part of the method, there is no client by that name
    60.         Return Nothing
    61.     End Function
    62. End Class
    ConnectedClient class:
    VB.Net Code:
    1. Public Class ConnectedClient
    2.     Private mClient As System.Net.Sockets.TcpClient
    3.  
    4.     Private mUsername As String
    5.     Private mParentForm As Form1
    6.     Private readThread As System.Threading.Thread
    7.     Private Const MESSAGE_DELIMITER As Char = ControlChars.Cr
    8.  
    9.     Public Event dataReceived(ByVal sender As ConnectedClient, ByVal message As String)
    10.  
    11.     Sub New(ByVal client As System.Net.Sockets.TcpClient, ByVal parentForm As Form1)
    12.         mParentForm = parentForm
    13.         mClient = client
    14.  
    15.         readThread = New System.Threading.Thread(AddressOf doRead)
    16.         readThread.IsBackground = True
    17.         readThread.Start()
    18.     End Sub
    19.  
    20.     Public Property Username() As String
    21.         Get
    22.             Return mUsername
    23.         End Get
    24.         Set(ByVal value As String)
    25.             mUsername = value
    26.         End Set
    27.     End Property
    28.  
    29.     Private Sub doRead()
    30.         Const BYTES_TO_READ As Integer = 255
    31.         Dim readBuffer(BYTES_TO_READ) As Byte
    32.         Dim bytesRead As Integer
    33.         Dim sBuilder As New System.Text.StringBuilder
    34.         Do
    35.             bytesRead = mClient.GetStream.Read(readBuffer, 0, BYTES_TO_READ)
    36.             If (bytesRead > 0) Then
    37.                 Dim message As String = System.Text.Encoding.UTF8.GetString(readBuffer, 0, bytesRead)
    38.                 If (message.IndexOf(MESSAGE_DELIMITER) > -1) Then
    39.  
    40.                     Dim subMessages() As String = message.Split(MESSAGE_DELIMITER)
    41.  
    42.                     'The first element in the subMessages string array must be the last part of the current message.
    43.                     'So we append it to the StringBuilder and raise the dataReceived event
    44.                     sBuilder.Append(subMessages(0))
    45.                     RaiseEvent dataReceived(Me, sBuilder.ToString)
    46.                     sBuilder = New System.Text.StringBuilder
    47.  
    48.                     'If there are only 2 elements in the array, we know that the second one is an incomplete message,
    49.                     'though if there are more then two then every element inbetween the first and the last are complete messages:
    50.                     If subMessages.Length = 2 Then
    51.                         sBuilder.Append(subMessages(1))
    52.                     Else
    53.                         For i As Integer = 1 To subMessages.GetUpperBound(0) - 1
    54.                             RaiseEvent dataReceived(Me, subMessages(i))
    55.                         Next
    56.                         sBuilder.Append(subMessages(subMessages.GetUpperBound(0)))
    57.                     End If
    58.                 Else
    59.  
    60.                     'MESSAGE_DELIMITER was not found in the message, so we just append everything to the stringbuilder.
    61.                     sBuilder.Append(message)
    62.                 End If
    63.             End If
    64.         Loop
    65.     End Sub
    66.  
    67.     Public Sub SendMessage(ByVal msg As String)
    68.         Dim sw As IO.StreamWriter
    69.         Try
    70.             SyncLock mClient.GetStream
    71.                 sw = New IO.StreamWriter(mClient.GetStream) 'Create a new streamwriter that will be writing directly to the networkstream.
    72.                 sw.Write(msg)
    73.                 sw.Flush()
    74.             End SyncLock
    75.         Catch ex As Exception
    76.             MessageBox.Show(ex.ToString)
    77.         End Try
    78.         'As opposed to writing to a file, we DONT call close on the streamwriter, since we dont want to close the stream.
    79.     End Sub
    80.  
    81. End Class

    Client Side:
    Form:
    VB.Net Code:
    1. Public Class Form1
    2.     Private client As System.Net.Sockets.TcpClient
    3.  
    4.     Private Const BYTES_TO_READ As Integer = 255
    5.     Private readBuffer(BYTES_TO_READ) As Byte
    6.  
    7.     Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    8.         client = New System.Net.Sockets.TcpClient("localhost", 43001)
    9.         client.GetStream.BeginRead(readBuffer, 0, BYTES_TO_READ, AddressOf doRead, Nothing)
    10.     End Sub
    11.  
    12.     Private Sub doRead(ByVal ar As System.IAsyncResult)
    13.         Dim totalRead As Integer
    14.         Try
    15.             totalRead = client.GetStream.EndRead(ar) 'Ends the reading and returns the number of bytes read.
    16.         Catch ex As Exception
    17.             'The underlying socket have probably been closed OR an error has occured whilst trying to access it, either way, this is where you should remove close all eventuall connections
    18.             'to this client and remove it from the list of connected clients.
    19.         End Try
    20.  
    21.             If totalRead > 0 Then
    22.                 'the readBuffer array will contain everything read from the client.
    23.                 Dim receivedString As String = System.Text.Encoding.UTF8.GetString(readBuffer, 0, totalRead)
    24.                 messageReceived(receivedString)
    25.             End If
    26.  
    27.             Try
    28.                 client.GetStream.BeginRead(readBuffer, 0, BYTES_TO_READ, AddressOf doRead, Nothing) 'Begin the reading again.
    29.             Catch ex As Exception
    30.                 'The underlying socket have probably been closed OR an error has occured whilst trying to access it, either way, this is where you should remove close all eventuall connections
    31.                 'to this client and remove it from the list of connected clients.
    32.             End Try
    33.     End Sub
    34.  
    35.     Private Sub messageReceived(ByVal message As String)
    36.         MessageBox.Show(message)
    37.     End Sub
    38.  
    39.  
    40.  
    41.     Private Sub SendMessage(ByVal msg As String)
    42.         Dim sw As IO.StreamWriter
    43.         Try
    44.             sw = New IO.StreamWriter(client.GetStream)
    45.             sw.Write(msg)
    46.             sw.Flush()
    47.         Catch ex As Exception
    48.             MessageBox.Show(ex.ToString)
    49.         End Try
    50.     End Sub
    51. End Class
    You need to add more exception handling and possibly some SyncLocks upon accessing the different Streams. There are also some important things that I've left out, such as removing a client from the list of connected client upon disconnection.
    I've tried to put some comments in the code but dont hesitate to look the different methods/classes up on MSDN.

    Edit: I intend to update this example some day soon.
    Last edited by Atheist; Apr 11th, 2009 at 07:23 AM.
    ---My Flickr photo (mostly screenshots these days!) stream. Have a look!

    Rate posts that helped you. I do not reply to PM's with coding questions.
    How to Get Your Questions Answered
    TCP client/server connection | Retrieving the EventHandler for any Event by code.
    Me on.. BitBucket, Google Code, Github (pretty empty)

  15. #15

    Thread Starter
    Addicted Member
    Join Date
    Dec 2007
    Posts
    167

    Re: [2008] Can I add a TCPClient Component

    thanks a million
    I will check this code and reply asap
    thanks again

  16. #16

    Thread Starter
    Addicted Member
    Join Date
    Dec 2007
    Posts
    167

    Re: [2008] Can I add a TCPClient Component

    ok ur code is perfect, just what i wanted
    now i have few questions:
    1) Im getting an error
    Cross-thread operation not valid: Control 'LblConnection' accessed from a thread other than the thread it was created on.
    when I did this:
    Code:
        Private Sub MessageReceived(ByVal sender As ConnectedClient, ByVal Message As String)        'A message has been received from one of the clients.        'To determine who its from, use the sender object.        'sender.SendMessage can be used to reply to the sender.        
            Select Case Message
                Case "/Connect"
                    sender.SendMessage("/Connected")
                    LblConnection.Text = "Connected"
                Case Else
                    txtMain.Text = txtMain.Text & Message & vbNewLine
            End Select
        End Sub
    2) after the server and the client are connected properly...
    how can I send more msgs from the server
    how can I reiceive more msgs on the client

    ur code seems only to work for the first msg??

    thx

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

    Re: [2008] Can I add a TCPClient Component

    1.
    That is because all socket code is running on a separate thread, in order to access the controls you need to use Invoke. Heres an example that will fix the problem you posted:
    VB.Net Code:
    1. Private Delegate Sub StringDelegate(text As String)
    2.  
    3. Private Sub SetConnectionLabelText(text As String)
    4. If Me.LblConnection.InvokeRequired Then
    5.     Me.Invoke(New StringDelegate(AddressOf SetConnectionLabelText), text)
    6. Else
    7.     Me.LblConnection.Text = text
    8. End If
    9. End Sub
    Now instead of doing:
    VB.Net Code:
    1. LblConnection.Text = "Connected"
    Do:
    VB.Net Code:
    1. SetConnectionLabelText("Connected")

    2.
    If you want to send messages from the server, simply iterate through the list of connected clients and call the SendMessage method on the client you want to send a message to.

    EDIT: Oh, I see that I've made a silly misstake in my code. Try it now.
    Last edited by Atheist; Jan 2nd, 2008 at 02:29 PM.
    ---My Flickr photo (mostly screenshots these days!) stream. Have a look!

    Rate posts that helped you. I do not reply to PM's with coding questions.
    How to Get Your Questions Answered
    TCP client/server connection | Retrieving the EventHandler for any Event by code.
    Me on.. BitBucket, Google Code, Github (pretty empty)

  18. #18

    Thread Starter
    Addicted Member
    Join Date
    Dec 2007
    Posts
    167

    Re: [2008] Can I add a TCPClient Component

    well.. can u elaborate more?
    Code:
        Private Sub BtnSend_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnSend.Click
               If txtSend.Text <> "" Then
              ' ????? should i use client.?????
              End If
        End Sub

  19. #19
    Frenzied Member
    Join Date
    Mar 2006
    Location
    Pennsylvania
    Posts
    1,069

    Re: [2008] Can I add a TCPClient Component

    Elaborate more? He just told you exactly what to do. What are you having problems with?

  20. #20

    Thread Starter
    Addicted Member
    Join Date
    Dec 2007
    Posts
    167

    Re: [2008] Can I add a TCPClient Component

    how to iterate through the list of connected clients ...
    sorry but its really not easy for me

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

    Re: [2008] Can I add a TCPClient Component

    You see, this is a collection:
    VB.Net Code:
    1. Private clients As New List(Of ConnectedClient)
    You can iterate through collections like this:
    VB.Net Code:
    1. For Each cc As ConnectedClient In clients
    2.     cc.SendMessage("this is a test")
    3. Next
    This will send a message to all connected clients.
    ---My Flickr photo (mostly screenshots these days!) stream. Have a look!

    Rate posts that helped you. I do not reply to PM's with coding questions.
    How to Get Your Questions Answered
    TCP client/server connection | Retrieving the EventHandler for any Event by code.
    Me on.. BitBucket, Google Code, Github (pretty empty)

  22. #22

    Thread Starter
    Addicted Member
    Join Date
    Dec 2007
    Posts
    167

    Re: [2008] Can I add a TCPClient Component

    i have another question
    when i send a msg from the client to the server using this code
    Code:
        Private Sub SendMessage(ByVal Msg As String)
            Dim sw As IO.StreamWriter
            Try
                sw = New IO.StreamWriter(client.GetStream)
                sw.Write(msg)
                sw.Flush()
            Catch ex As Exception
                MessageBox.Show(ex.ToString)
            End Try
        End Sub
    I have to send the msg twice for it to reach the server
    its like this, firsrt the two programs connect and the client send "/connect" and the server recieves it, then whatever the client sends the server doesnt recieve it.
    the third msg is recieved, the fourth is not....

    why is this happeneing?

    2) how to read msgs in the client program?? my client only sends now...
    should I create a Public Class ConnectedClient in the client program also?
    Last edited by perito; Jan 3rd, 2008 at 10:33 AM.

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

    Re: [2008] Can I add a TCPClient Component

    About your first question, it was a small misstake I had made in the code that is now fixed, I've edited the original code in my previous post.

    As for your second question, I cant see how I forgot to add that, hold on..
    ---My Flickr photo (mostly screenshots these days!) stream. Have a look!

    Rate posts that helped you. I do not reply to PM's with coding questions.
    How to Get Your Questions Answered
    TCP client/server connection | Retrieving the EventHandler for any Event by code.
    Me on.. BitBucket, Google Code, Github (pretty empty)

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

    Re: [2008] Can I add a TCPClient Component

    There, I've edited the code to handle incoming messages on the client side.
    ---My Flickr photo (mostly screenshots these days!) stream. Have a look!

    Rate posts that helped you. I do not reply to PM's with coding questions.
    How to Get Your Questions Answered
    TCP client/server connection | Retrieving the EventHandler for any Event by code.
    Me on.. BitBucket, Google Code, Github (pretty empty)

  25. #25

    Thread Starter
    Addicted Member
    Join Date
    Dec 2007
    Posts
    167

    Re: [2008] Can I add a TCPClient Component

    handling incoming messages worked perfectly... but am I blind because I cant see any difference in the rest of the code?
    what should I chage to stop sending the msg twice before it was read?

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

    Re: [2008] Can I add a TCPClient Component

    Quote Originally Posted by perito
    handling incoming messages worked perfectly... but am I blind because I cant see any difference in the rest of the code?
    what should I chage to stop sending the msg twice before it was read?
    I made a small change in the doListen subroutine on the server side.
    ---My Flickr photo (mostly screenshots these days!) stream. Have a look!

    Rate posts that helped you. I do not reply to PM's with coding questions.
    How to Get Your Questions Answered
    TCP client/server connection | Retrieving the EventHandler for any Event by code.
    Me on.. BitBucket, Google Code, Github (pretty empty)

  27. #27

    Thread Starter
    Addicted Member
    Join Date
    Dec 2007
    Posts
    167

    Re: [2008] Can I add a TCPClient Component

    THANKS...............
    thanks a million, the program works fine now

    I still have a couple questions to improve the code now :P
    first, on the server side,
    how to see the ConnectedClient List? (for example put it in ListBox1) so we can send seperate msgs?
    thanks agian

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

    Re: [2008] Can I add a TCPClient Component

    Well, since you dont have any good unique identifier like a username or something of the sort, you have 3 options:

    1. Simply add each ConnectedClient instance in the collection to the Listbox, since the listbox can have any kind of object added to it. This wont be pretty as each item will look the same in the listbox..something like this: [ProjectName].UserConnection
    The only advantage is that the listbox will return a ConnectedClient in the SelectedItem property that you can use easily:
    VB.Net Code:
    1. Ctype(ListBox1.SelectedItem, ConnectedClient).SendMessage("hello")

    2. This is another option:
    VB.Net Code:
    1. For i As Integer = 0 To clients.Count-1
    2.     ListBox1.Items.Add(i)
    3. Next i
    Each client will now be represented by their index in the listbox. To send a message to a client by index you do:
    VB.Net Code:
    1. clients.item(Cint(ListBox1.SelectedItem)).SendMessage("hello")

    3. The final option: This is the best option if you want to be able to identify a specific client from the rest.
    Upon connection, have the client send a username that it wants to use. The server receives the username, checks so that it isnt already in use, then assigns it to the instance of ConnectedClient from which the message was received. This username can then be used to display every client in a list.
    ---My Flickr photo (mostly screenshots these days!) stream. Have a look!

    Rate posts that helped you. I do not reply to PM's with coding questions.
    How to Get Your Questions Answered
    TCP client/server connection | Retrieving the EventHandler for any Event by code.
    Me on.. BitBucket, Google Code, Github (pretty empty)

  29. #29

    Thread Starter
    Addicted Member
    Join Date
    Dec 2007
    Posts
    167

    Re: [2008] Can I add a TCPClient Component

    ok so Im tring to build the third option
    so I have this code
    Code:
        Private Sub MessageReceived(ByVal sender As ConnectedClient, ByVal Message As String)        'A message has been received from one of the clients.        'To determine who its from, use the sender object.        'sender.SendMessage can be used to reply to the sender.        
            If Mid(Message, 1, 1) = "/" Then
                Select Case Mid(Message, 2, 8)
                    Case "Connect:"
                        sender.SendMessage("/Connected")
                        SetConnectionLabelText("Connected")
                    Case Else
                        WriteToMainText(Message)
                End Select
            End If
        End Sub
    considering the cilent send "/Connect:USERNAME" when it connects
    how to add the username to the list?

    I was checking ur previous topic and u had a different diclaration
    Dim Clients As New Dictionary(Of String, Net.Sockets.TcpClient)

    whats the difference?
    and u added the name in DoListen Sub not MessageReceived Sub?
    what should I do?

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

    Re: [2008] Can I add a TCPClient Component

    Quote Originally Posted by perito
    ok so Im tring to build the third option
    so I have this code
    Code:
        Private Sub MessageReceived(ByVal sender As ConnectedClient, ByVal Message As String)        'A message has been received from one of the clients.        'To determine who its from, use the sender object.        'sender.SendMessage can be used to reply to the sender.        
            If Mid(Message, 1, 1) = "/" Then
                Select Case Mid(Message, 2, 8)
                    Case "Connect:"
                        sender.SendMessage("/Connected")
                        SetConnectionLabelText("Connected")
                    Case Else
                        WriteToMainText(Message)
                End Select
            End If
        End Sub
    considering the cilent send "/Connect:USERNAME" when it connects
    how to add the username to the list?

    I was checking ur previous topic and u had a different diclaration
    Dim Clients As New Dictionary(Of String, Net.Sockets.TcpClient)

    whats the difference?
    and u added the name in DoListen Sub not MessageReceived Sub?
    what should I do?
    Alright, start by creating a string variable for holding the username in the ConnectedClient class, and create a string property for it. (If you dont know how, I'll shortly update my example). This variable will (obviously) hold the clients username.

    Heres a method of handling messages used in MSDN 101 examples:
    Send the messages with the | character as separator. If the user wants to connect with a username he'd send this: "CONNECT|MyName"

    Your messageReceived method would then look like this:
    VB.Net Code:
    1. Private Sub messageReceived(ByVal sender As ConnectedClient, ByVal message As String)
    2.         'A message has been received from one of the clients.
    3.         'To determine who its from, use the sender object.
    4.         'sender.SendMessage can be used to reply to the sender.
    5.  
    6.         Dim data() As String = message.Split("|"c) 'Split the message on each | and place in the string array.
    7.         Select Case data(0)
    8.             Case "CONNECT"
    9.                 'We use GetClientByName to make sure no one else is using this username.
    10.                 'It will return Nothing if the username is free.
    11.                 'Since the client sent the message in this format: CONNECT|UserName, the username will be in the array on index 1.
    12.                 If GetClientByName(data(1)) Is Nothing Then
    13.                     'The username is not taken, we can safely assign it to the sender.
    14.                     sender.Username = data(1)
    15.                 End If
    16.         End Select
    17.  
    18.     End Sub
    19.  
    20.     Private Function GetClientByName(ByVal name As String) As ConnectedClient
    21.         For Each cc As ConnectedClient In clients
    22.             If cc.Username = name Then
    23.                 Return cc 'client found, return it.
    24.             End If
    25.         Next
    26.         'If we've reached this part of the method, there is no client by that name
    27.         Return Nothing
    28.     End Function
    Note the GetClientByName function, it will be useful later aswell.

    About my use of the Dictionary in the other example, it provides the functionallity to store items in a collection and let each item have a (in this case) string key to identify them. We could've used that in this code aswell, but I chose the List instead.

    Also, ignore all my other code in that example, the examples in there are fairly simple and nothing you should be using.
    ---My Flickr photo (mostly screenshots these days!) stream. Have a look!

    Rate posts that helped you. I do not reply to PM's with coding questions.
    How to Get Your Questions Answered
    TCP client/server connection | Retrieving the EventHandler for any Event by code.
    Me on.. BitBucket, Google Code, Github (pretty empty)

  31. #31
    Lively Member
    Join Date
    May 2007
    Posts
    87

    Re: [2008] Can I add a TCPClient Component

    Hey there i did something like atheist did 2.
    I personaly did it with creating a new class wich has as property ConnectedClient or a connected socket or something.(notice i worked with winsock so my own class had a connected winsock class in it) This way you can store anything you like from that user even if you want (while making a game) its position in your screen/world.

    Greets

  32. #32

    Thread Starter
    Addicted Member
    Join Date
    Dec 2007
    Posts
    167

    Re: [2008] Can I add a TCPClient Component

    ok, first in the above code we did
    Code:
        Private Sub DoListen()
            Dim incomingClient As System.Net.Sockets.TcpClient
            Do
                incomingClient = listener.AcceptTcpClient 'Accept the incoming connection. This is a blocking method so execution will halt here until someone tries to connect.            
                Dim connClient As New ConnectedClient(incomingClient) 'Create a new instance of ConnectedClient (check its constructor to see whats happening now).            
                ' clients.Add(New ConnectedClient(incomingClient)) 'Adds the connected client to the list of connected clients.            
                clients.Add(connClient) 'Adds the connected client to the list of connected clients.
                AddHandler connClient.dataReceived, AddressOf Me.MessageReceived
            Loop
        End Sub
    to add the new client ... should we remove it from here since we're going to add it in the MessageRecieved?

    could u tell me how to create a string variable for holding the username in the ConnectedClient class, and create a string property for it...
    thanks

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

    Re: [2008] Can I add a TCPClient Component

    Quote Originally Posted by perito
    ok, first in the above code we did
    Code:
        Private Sub DoListen()
            Dim incomingClient As System.Net.Sockets.TcpClient
            Do
                incomingClient = listener.AcceptTcpClient 'Accept the incoming connection. This is a blocking method so execution will halt here until someone tries to connect.            
                Dim connClient As New ConnectedClient(incomingClient) 'Create a new instance of ConnectedClient (check its constructor to see whats happening now).            
                ' clients.Add(New ConnectedClient(incomingClient)) 'Adds the connected client to the list of connected clients.            
                clients.Add(connClient) 'Adds the connected client to the list of connected clients.
                AddHandler connClient.dataReceived, AddressOf Me.MessageReceived
            Loop
        End Sub
    to add the new client ... should we remove it from here since we're going to add it in the MessageRecieved?

    could u tell me how to create a string variable for holding the username in the ConnectedClient class, and create a string property for it...
    thanks
    No we shouldnt remove it from that collection. Keep that method as it is
    I'll edit the original code in my above post. Watch it closely

    EDIT: There, take a look at the code for the ConnectedClient class, specificly at the mUsername variable and the Username property.
    Last edited by Atheist; Jan 3rd, 2008 at 12:40 PM.
    ---My Flickr photo (mostly screenshots these days!) stream. Have a look!

    Rate posts that helped you. I do not reply to PM's with coding questions.
    How to Get Your Questions Answered
    TCP client/server connection | Retrieving the EventHandler for any Event by code.
    Me on.. BitBucket, Google Code, Github (pretty empty)

  34. #34

    Thread Starter
    Addicted Member
    Join Date
    Dec 2007
    Posts
    167

    Re: [2008] Can I add a TCPClient Component

    Excelent!
    So now, each time a new client connects to my server, its username will be added to the listbox lbClients
    How to send a msg to a specific Client (the one which is selected in the list box?)

    thanks

  35. #35
    Fanatic Member
    Join Date
    Jul 2007
    Posts
    530

    Re: [2008] Can I add a TCPClient Component

    @perito

    Can You Post Your Full Code That is Working For You Now
    I am also interested

  36. #36

    Thread Starter
    Addicted Member
    Join Date
    Dec 2007
    Posts
    167

    Re: [2008] Can I add a TCPClient Component

    @killer7k
    sure Ill post the code when I finish the program
    although this is pretty much it
    http://www.vbforums.com/showpost.php...2&postcount=14

    anyway, to all moderators and admins
    PLEASE could you make this topic sticky or add it to the tut sections
    u cant edit it if u want, but I kept searching for 4 days before atheist started helping me. Before his help, I couldnt find anything, everything on the web is 100x more complicated.

    If anyone could turn this thread to a tut, that would be great !!
    Please give credits to Atheist if u do so.

    Thanks

    @Atheist
    could u plz reply to my previous question?

  37. #37
    Fanatic Member
    Join Date
    Jul 2007
    Posts
    530

    Re: [2008] Can I add a TCPClient Component

    oK Thanks m8

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

    Re: [2008] Can I add a TCPClient Component

    Quote Originally Posted by perito
    Excelent!
    So now, each time a new client connects to my server, its username will be added to the listbox lbClients
    How to send a msg to a specific Client (the one which is selected in the list box?)

    thanks
    You retrieve the selected username by using the SelectedItem property of the listbox (it returns an Object so it needs to be converted to a string).
    You use the GetClientByName function to get the ConnectedClient instance connected to the username. Once you have it, call its SendMessage method.
    ---My Flickr photo (mostly screenshots these days!) stream. Have a look!

    Rate posts that helped you. I do not reply to PM's with coding questions.
    How to Get Your Questions Answered
    TCP client/server connection | Retrieving the EventHandler for any Event by code.
    Me on.. BitBucket, Google Code, Github (pretty empty)

  39. #39

    Thread Starter
    Addicted Member
    Join Date
    Dec 2007
    Posts
    167

    Re: [2008] Can I add a TCPClient Component

    OK, it worked gr8
    Now how to figure out if a client disconnected from my server?
    thx

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

    Re: [2008] Can I add a TCPClient Component

    Quote Originally Posted by perito
    OK, it worked gr8
    Now how to figure out if a client disconnected from my server?
    thx
    The ideal thing is to have the client send a message whenever it closes down. When the server receives this message it should simply remove him from the list of connected clients.

    However, if the client closes because of the system crashing or something of the sort, sending a message is obviously not possible. We will solve this by adding some nifty code when the exception occures in the doRead subroutine. But in order to do this we will need to change the ConnectedClients constructor, I'm going to update the code again..

    Edit: There now I've edited the code.
    Notice the new constructor in the ConnectedClient class, it takes one more argument, an the instance of Form1.
    So upon creating a new ConnectedClient class, (on the doListen subroutine) we pass it like so: New ConnectedClass(incomingClient, Me)

    This is because we want to call the new subroutine 'removeClient' from within ConnectedClass, like you can see being done in the doRead subroutine.
    I hope this isnt too confusing for you
    Last edited by Atheist; Jan 4th, 2008 at 08:10 AM.
    ---My Flickr photo (mostly screenshots these days!) stream. Have a look!

    Rate posts that helped you. I do not reply to PM's with coding questions.
    How to Get Your Questions Answered
    TCP client/server connection | Retrieving the EventHandler for any Event by code.
    Me on.. BitBucket, Google Code, Github (pretty empty)

Page 1 of 5 1234 ... LastLast

Posting Permissions

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



Featured


Click Here to Expand Forum to Full Width

Survey posted by VBForums.