Results 1 to 3 of 3

Thread: TCP Server and Client (Using code from "Athiest")

  1. #1

    Thread Starter
    Member
    Join Date
    Jun 2009
    Posts
    47

    TCP Server and Client (Using code from "Athiest")

    Using the VB.net code from Athiest's post I have got a TCP server and client working, my problem is the Server side is too confusing and has too much functionality that I do not need. Using the below code I can get the server to send the client a message and I can have the client display that in a Message Box, I can also have the Client send the Server a message but I cannot get the server to display that text in a message box.

    Here is the code, there is a server and connected client (server side) and then there is the client side (It is in the next post as the post was too large for the forum):

  2. #2

    Thread Starter
    Member
    Join Date
    Jun 2009
    Posts
    47

    Re: TCP Server and Client (Using code from "Athiest")

    Server 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, 60000) '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.                     MsgBox(sender.Username)
    47.                 End If
    48.             Case "DISCONNECT"
    49.                 removeClient(sender)
    50.         End Select
    51.  
    52.     End Sub
    53.  
    54.     Private Function GetClientByName(ByVal name As String) As ConnectedClient
    55.         For Each cc As ConnectedClient In clients
    56.             If cc.Username = name Then
    57.                 Return cc 'client found, return it.
    58.             End If
    59.         Next
    60.         'If we've reached this part of the method, there is no client by that name
    61.         Return Nothing
    62.     End Function
    63.  
    64.     Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    65.         For Each cc As ConnectedClient In clients
    66.             cc.SendMessage("this is a test and my name is......... hello thomas hahaha" & ControlChars.Cr)
    67.         Next
    68.     End Sub
    69. End Class

    Connected Client 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

  3. #3

    Thread Starter
    Member
    Join Date
    Jun 2009
    Posts
    47

    Re: TCP Server and Client (Using code from "Athiest")

    Client Code:
    1. Public Class Form1
    2.     Private client As System.Net.Sockets.TcpClient
    3.  
    4.     Private Const MESSAGE_DELIMITER As Char = ControlChars.Cr
    5.     Private readThread As System.Threading.Thread
    6.  
    7.     Private Delegate Sub messageReceivedCallBack(ByVal msg As String)
    8.  
    9.  
    10.     Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    11.         client = New System.Net.Sockets.TcpClient("localhost", 60000)
    12.         readThread = New System.Threading.Thread(AddressOf doRead)
    13.         readThread.Start()
    14.     End Sub
    15.  
    16.     Private Sub doRead()
    17.         Const BYTES_TO_READ As Integer = 255
    18.         Dim readBuffer(BYTES_TO_READ) As Byte
    19.         Dim bytesRead As Integer
    20.         Dim sBuilder As New System.Text.StringBuilder
    21.         Do
    22.             bytesRead = client.GetStream.Read(readBuffer, 0, BYTES_TO_READ)
    23.             If (bytesRead > 0) Then
    24.                 Dim message As String = System.Text.Encoding.UTF8.GetString(readBuffer, 0, bytesRead)
    25.                 If (message.IndexOf(MESSAGE_DELIMITER) > -1) Then
    26.  
    27.                     Dim subMessages() As String = message.Split(MESSAGE_DELIMITER)
    28.  
    29.                     'The first element in the subMessages string array must be the last part of the current message.
    30.                     'So we append it to the StringBuilder and raise the dataReceived event
    31.                     sBuilder.Append(subMessages(0))
    32.                     Me.Invoke(New messageReceivedCallBack(AddressOf messageReceived), sBuilder.ToString())
    33.                     sBuilder = New System.Text.StringBuilder
    34.  
    35.                     'If there are only 2 elements in the array, we know that the second one is an incomplete message,
    36.                     'though if there are more then two then every element inbetween the first and the last are complete messages:
    37.                     If subMessages.Length = 2 Then
    38.                         sBuilder.Append(subMessages(1))
    39.                     Else
    40.                         For i As Integer = 1 To subMessages.GetUpperBound(0) - 1
    41.                             Me.Invoke(New messageReceivedCallBack(AddressOf messageReceived), subMessages(i))
    42.                         Next
    43.                         sBuilder.Append(subMessages(subMessages.GetUpperBound(0)))
    44.                     End If
    45.                 Else
    46.  
    47.                     'MESSAGE_DELIMITER was not found in the message, so we just append everything to the stringbuilder.
    48.                     sBuilder.Append(message)
    49.                 End If
    50.             End If
    51.         Loop
    52.     End Sub
    53.  
    54.     Private Sub messageReceived(ByVal message As String)
    55.         MessageBox.Show(message)
    56.     End Sub
    57.  
    58.     Private Sub SendMessage(ByVal msg As String)
    59.         Dim sw As IO.StreamWriter
    60.         Try
    61.             sw = New IO.StreamWriter(client.GetStream)
    62.             sw.Write(msg)
    63.             sw.Flush()
    64.         Catch ex As Exception
    65.             MessageBox.Show(ex.ToString)
    66.         End Try
    67.     End Sub
    68.  
    69.     Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    70.         SendMessage("Hello Server" & ControlChars.Cr)
    71.     End Sub
    72.  
    73. End Class

    I would like to do away with the "Connected Client" all together, is someone able to strip the server/Connected Client down so it is only one. I just want to be able to send messages from the client to the server and have the server be able to accept that and then do something with it like display that text in a MsgBox.

    Cheers,
    Richard

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