Results 1 to 1 of 1

Thread: Socket Client/Server not working

  1. #1

    Thread Starter
    Hyperactive Member
    Join Date
    Sep 2005
    Location
    Alaska
    Posts
    435

    Socket Client/Server not working

    I took the standard VB.NET 101 samples Socket chat project and fit it together with my code. But for some reason the server wont display the messages sent by the client and the client wont display the messages of the server.

    I loaded the exact non-edited sample and it had the same errors. Also note I disabled all my firewall tools

    Server (Excluding Userconnections.vb):
    VB Code:
    1. Const PORT_NUM As Integer = 29016
    2.  
    3.     Private clients As New Hashtable()
    4.     Private listener As TcpListener
    5.     Private listenerThread As Threading.Thread
    6.  
    7.     ' This subroutine sends a message to all attached clients
    8.     Public Sub Broadcast(ByVal strMessage As String)
    9.         Dim client As UserConnection
    10.         Dim entry As DictionaryEntry
    11.  
    12.         ' All entries in the clients Hashtable are UserConnection so it is possible
    13.         ' to assign it safely.
    14.         For Each entry In clients
    15.             client = CType(entry.Value, UserConnection)
    16.             client.SendData(strMessage)
    17.         Next
    18.     End Sub
    19.     Public Sub ConnectUser(ByVal userName As String, ByVal sender As UserConnection)
    20.         If clients.Contains(userName) Then
    21.             ReplyToSender("REFUSE", sender)
    22.         Else
    23.             sender.Name = userName
    24.             UpdateStatus(userName & " has joined the chat.")
    25.             clients.Add(userName, sender)
    26.             ListBox2.Items.Add(userName)
    27.  
    28.             ' Send a JOIN to sender, and notify all other clients that sender joined
    29.             ReplyToSender("JOIN", sender)
    30.             SendToClients("CHAT|" & sender.Name & " has joined the chat.", sender)
    31.         End If
    32.     End Sub
    33.     Public Sub DisconnectUser(ByVal sender As UserConnection)
    34.         UpdateStatus(sender.Name & " has left the chat.")
    35.         SendToClients("CHAT|" & sender.Name & " has left the chat.", sender)
    36.         clients.Remove(sender.Name)
    37.     End Sub
    38.     Public Sub DoListen()
    39.         Try
    40.             ' Listen for new connections.
    41.             listener = New TcpListener(System.Net.IPAddress.Any, PORT_NUM)
    42.             listener.Start()
    43.             Do
    44.                 ' Create a new user connection using TcpClient returned by
    45.                 ' TcpListener.AcceptTcpClient()
    46.                 Dim client As New UserConnection(listener.AcceptTcpClient)
    47.  
    48.                 ' Create an event handler to allow the UserConnection to communicate
    49.                 ' with the window.
    50.                 AddHandler client.LineReceived, AddressOf OnLineReceived
    51.                 UpdateStatus("New connection found: waiting for log-in")
    52.             Loop Until False
    53.         Catch
    54.         End Try
    55.     End Sub
    56.     Public Sub ListUsers(ByVal sender As UserConnection)
    57.         Dim client As UserConnection
    58.         Dim entry As DictionaryEntry
    59.         Dim strUserList As String
    60.  
    61.         UpdateStatus("Sending " & sender.Name & " a list of users online.")
    62.  
    63.         strUserList = "LISTUSERS"
    64.  
    65.         ' All entries in the clients Hashtable are UserConnection so it is possible
    66.         ' to assign it safely.
    67.         For Each entry In clients
    68.             client = CType(entry.Value, UserConnection)
    69.             strUserList = strUserList & "|" & client.Name
    70.         Next
    71.  
    72.         ' Send the list to the sender.
    73.         ReplyToSender(strUserList, sender)
    74.     End Sub
    75.     Public Sub OnLineReceived(ByVal sender As UserConnection, ByVal data As String)
    76.         Dim dataArray() As String
    77.  
    78.         ' Message parts are divided by "|"  Break the string into an array accordingly.
    79.         dataArray = data.Split(Chr(124))
    80.  
    81.         ' dataArray(0) is the command.
    82.         Select Case dataArray(0)
    83.             Case "CONNECT"
    84.                 ConnectUser(dataArray(1), sender)
    85.             Case "CHAT"
    86.                 SendChat(dataArray(1), sender)
    87.             Case "DISCONNECT"
    88.                 DisconnectUser(sender)
    89.             Case "REQUESTUSERS"
    90.                 ListUsers(sender)
    91.             Case Else
    92.                 UpdateStatus("Unknown message:" & data)
    93.         End Select
    94.     End Sub
    95.     Public Sub ReplyToSender(ByVal strMessage As String, ByVal sender As UserConnection)
    96.         sender.SendData(strMessage)
    97.     End Sub
    98.  
    99.     ' Send a chat message to all clients except sender.
    100.     Public Sub SendChat(ByVal message As String, ByVal sender As UserConnection)
    101.         UpdateStatus(sender.Name & ": " & message)
    102.         SendToClients("CHAT|" & sender.Name & ": " & message, sender)
    103.     End Sub
    104.  
    105.     ' This subroutine sends a message to all attached clients except the sender.
    106.     Public Sub SendToClients(ByVal strMessage As String, ByVal sender As UserConnection)
    107.         Dim client As UserConnection
    108.         Dim entry As DictionaryEntry
    109.  
    110.         ' All entries in the clients Hashtable are UserConnection so it is possible
    111.         ' to assign it safely.
    112.         For Each entry In clients
    113.             client = CType(entry.Value, UserConnection)
    114.  
    115.             ' Exclude the sender.
    116.             If client.Name <> sender.Name Then
    117.                 client.SendData(strMessage)
    118.             End If
    119.         Next
    120.     End Sub
    121.  
    122.     ' This subroutine adds line to the Status listbox
    123.     Public Sub UpdateStatus(ByVal statusMessage As String)
    124.         ListBox1.Items.Add(statusMessage)
    125.     End Sub
    126.     Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    127.         listenerThread = New Threading.Thread(AddressOf DoListen)
    128.         listenerThread.Start()
    129.         UpdateStatus("Listener started")
    130.  
    131.     End Sub
    132.  
    133.     Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
    134.         If TextBox2.Text <> "" Then
    135.             UpdateStatus("Broadcasting: " & TextBox2.Text)
    136.             Broadcast("BROAD|" & TextBox2.Text)
    137.  
    138.             TextBox2.Text = ""
    139.         End If
    140.     End Sub

    Client: Also, the client does say it connected.
    VB Code:
    1. Imports System.Net.Sockets
    2. Imports System.Text
    3. Public Class frm_Main
    4.     Const READ_BUFFER_SIZE As Integer = 255
    5.     Const PORT_NUM As Integer = 29016
    6.  
    7.     Private client As TcpClient
    8.     Private readBuffer(READ_BUFFER_SIZE) As Byte
    9.  
    10.     ' Pop up a Connect user dialog and send a message requesting user to log in to chat.
    11.     Public Sub AttemptLogin()
    12.         SendData("CONNECT|" & My.Computer.Name)
    13.     End Sub
    14.     Public Sub DisplayText(ByVal text As String)
    15.         consoleL.Text = consoleL.Text + vbNewLine + text
    16.     End Sub
    17.     Public Sub DoRead(ByVal ar As IAsyncResult)
    18.         Dim BytesRead As Integer
    19.         Dim strMessage As String
    20.  
    21.         Try
    22.             ' Finish asynchronous read into readBuffer and return number of bytes read.
    23.             BytesRead = client.GetStream.EndRead(ar)
    24.             If BytesRead < 1 Then
    25.                 ' If no bytes were read server has close.  Disable input window.
    26.                 MarkAsDisconnected()
    27.                 Exit Sub
    28.             End If
    29.  
    30.             ' Convert the byte array the message was saved into, minus two for the
    31.             ' Chr(13) and Chr(10)
    32.             strMessage = Encoding.ASCII.GetString(readBuffer, 0, BytesRead - 2)
    33.  
    34.             ProcessCommands(strMessage)
    35.  
    36.             ' Start a new asynchronous read into readBuffer.
    37.             client.GetStream.BeginRead(readBuffer, 0, READ_BUFFER_SIZE, AddressOf DoRead, Nothing)
    38.         Catch e As Exception
    39.             MarkAsDisconnected()
    40.         End Try
    41.     End Sub
    42.     Public Sub Connect()
    43.         Try
    44.             ' The TcpClient is a subclass of Socket, providing higher level
    45.             ' functionality like streaming.
    46.             client = New TcpClient("localhost", PORT_NUM)
    47.  
    48.             ' Start an asynchronous read invoking DoRead to avoid lagging the user
    49.             ' interface.
    50.             client.GetStream.BeginRead(readBuffer, 0, READ_BUFFER_SIZE, AddressOf DoRead, Nothing)
    51.  
    52.             ' Make sure the window is showing before popping up connection dialog.
    53.  
    54.             AttemptLogin()
    55.             DisplayText("Connected to server")
    56.         Catch Ex As Exception
    57.             DisplayText("ERROR: Server is not active.  Please start server and try again.")
    58.         End Try
    59.     End Sub
    60.  
    61.     ' When the server disconnects, prevent further chat messages from being sent.
    62.     Public Sub MarkAsDisconnected()
    63.         Button2.Enabled = False
    64.     End Sub
    65.  
    66.     ' Process the command received from the server, and take appropriate action.
    67.     Public Sub ProcessCommands(ByVal strMessage As String)
    68.         Dim dataArray() As String
    69.  
    70.         ' Message parts are divided by "|"  Break the string into an array accordingly.
    71.         dataArray = strMessage.Split(Chr(124))
    72.  
    73.         ' dataArray(0) is the command.
    74.         Select Case dataArray(0)
    75.             Case "JOIN"
    76.                 ' Server acknowledged login.
    77.                 DisplayText("You have joined the chat" & Chr(13) & Chr(10))
    78.             Case "CHAT"
    79.                 ' Received chat message, display it.
    80.                 DisplayText(dataArray(1) & Chr(13) & Chr(10))
    81.             Case "REFUSE"
    82.                 ' Server refused login with this user name, try to log in with another.
    83.                 AttemptLogin()
    84.             Case "BROAD"
    85.                 ' Server sent a broadcast message
    86.                 DisplayText("ServerMessage: " & dataArray(1) & Chr(13) & Chr(10))
    87.         End Select
    88.     End Sub
    89.  
    90.     ' Use a StreamWriter to send a message to server.
    91.     Public Sub SendData(ByVal data As String)
    92.         Dim writer As New IO.StreamWriter(client.GetStream)
    93.         writer.Write(data & vbCr)
    94.         writer.Flush()
    95.     End Sub
    Last edited by tylerm; Feb 25th, 2006 at 09:54 PM.

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