PDA

Click to See Complete Forum and Search --> : Socket Client/Server not working


tylerm
Feb 25th, 2006, 08:49 PM
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):
Const PORT_NUM As Integer = 29016

Private clients As New Hashtable()
Private listener As TcpListener
Private listenerThread As Threading.Thread

' This subroutine sends a message to all attached clients
Public Sub Broadcast(ByVal strMessage As String)
Dim client As UserConnection
Dim entry As DictionaryEntry

' All entries in the clients Hashtable are UserConnection so it is possible
' to assign it safely.
For Each entry In clients
client = CType(entry.Value, UserConnection)
client.SendData(strMessage)
Next
End Sub
Public Sub ConnectUser(ByVal userName As String, ByVal sender As UserConnection)
If clients.Contains(userName) Then
ReplyToSender("REFUSE", sender)
Else
sender.Name = userName
UpdateStatus(userName & " has joined the chat.")
clients.Add(userName, sender)
ListBox2.Items.Add(userName)

' Send a JOIN to sender, and notify all other clients that sender joined
ReplyToSender("JOIN", sender)
SendToClients("CHAT|" & sender.Name & " has joined the chat.", sender)
End If
End Sub
Public Sub DisconnectUser(ByVal sender As UserConnection)
UpdateStatus(sender.Name & " has left the chat.")
SendToClients("CHAT|" & sender.Name & " has left the chat.", sender)
clients.Remove(sender.Name)
End Sub
Public Sub DoListen()
Try
' Listen for new connections.
listener = New TcpListener(System.Net.IPAddress.Any, PORT_NUM)
listener.Start()
Do
' Create a new user connection using TcpClient returned by
' TcpListener.AcceptTcpClient()
Dim client As New UserConnection(listener.AcceptTcpClient)

' Create an event handler to allow the UserConnection to communicate
' with the window.
AddHandler client.LineReceived, AddressOf OnLineReceived
UpdateStatus("New connection found: waiting for log-in")
Loop Until False
Catch
End Try
End Sub
Public Sub ListUsers(ByVal sender As UserConnection)
Dim client As UserConnection
Dim entry As DictionaryEntry
Dim strUserList As String

UpdateStatus("Sending " & sender.Name & " a list of users online.")

strUserList = "LISTUSERS"

' All entries in the clients Hashtable are UserConnection so it is possible
' to assign it safely.
For Each entry In clients
client = CType(entry.Value, UserConnection)
strUserList = strUserList & "|" & client.Name
Next

' Send the list to the sender.
ReplyToSender(strUserList, sender)
End Sub
Public Sub OnLineReceived(ByVal sender As UserConnection, ByVal data As String)
Dim dataArray() As String

' Message parts are divided by "|" Break the string into an array accordingly.
dataArray = data.Split(Chr(124))

' dataArray(0) is the command.
Select Case dataArray(0)
Case "CONNECT"
ConnectUser(dataArray(1), sender)
Case "CHAT"
SendChat(dataArray(1), sender)
Case "DISCONNECT"
DisconnectUser(sender)
Case "REQUESTUSERS"
ListUsers(sender)
Case Else
UpdateStatus("Unknown message:" & data)
End Select
End Sub
Public Sub ReplyToSender(ByVal strMessage As String, ByVal sender As UserConnection)
sender.SendData(strMessage)
End Sub

' Send a chat message to all clients except sender.
Public Sub SendChat(ByVal message As String, ByVal sender As UserConnection)
UpdateStatus(sender.Name & ": " & message)
SendToClients("CHAT|" & sender.Name & ": " & message, sender)
End Sub

' This subroutine sends a message to all attached clients except the sender.
Public Sub SendToClients(ByVal strMessage As String, ByVal sender As UserConnection)
Dim client As UserConnection
Dim entry As DictionaryEntry

' All entries in the clients Hashtable are UserConnection so it is possible
' to assign it safely.
For Each entry In clients
client = CType(entry.Value, UserConnection)

' Exclude the sender.
If client.Name <> sender.Name Then
client.SendData(strMessage)
End If
Next
End Sub

' This subroutine adds line to the Status listbox
Public Sub UpdateStatus(ByVal statusMessage As String)
ListBox1.Items.Add(statusMessage)
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
listenerThread = New Threading.Thread(AddressOf DoListen)
listenerThread.Start()
UpdateStatus("Listener started")

End Sub

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
If TextBox2.Text <> "" Then
UpdateStatus("Broadcasting: " & TextBox2.Text)
Broadcast("BROAD|" & TextBox2.Text)

TextBox2.Text = ""
End If
End Sub

Client: Also, the client does say it connected.
Imports System.Net.Sockets
Imports System.Text
Public Class frm_Main
Const READ_BUFFER_SIZE As Integer = 255
Const PORT_NUM As Integer = 29016

Private client As TcpClient
Private readBuffer(READ_BUFFER_SIZE) As Byte

' Pop up a Connect user dialog and send a message requesting user to log in to chat.
Public Sub AttemptLogin()
SendData("CONNECT|" & My.Computer.Name)
End Sub
Public Sub DisplayText(ByVal text As String)
consoleL.Text = consoleL.Text + vbNewLine + text
End Sub
Public Sub DoRead(ByVal ar As IAsyncResult)
Dim BytesRead As Integer
Dim strMessage As String

Try
' Finish asynchronous read into readBuffer and return number of bytes read.
BytesRead = client.GetStream.EndRead(ar)
If BytesRead < 1 Then
' If no bytes were read server has close. Disable input window.
MarkAsDisconnected()
Exit Sub
End If

' Convert the byte array the message was saved into, minus two for the
' Chr(13) and Chr(10)
strMessage = Encoding.ASCII.GetString(readBuffer, 0, BytesRead - 2)

ProcessCommands(strMessage)

' Start a new asynchronous read into readBuffer.
client.GetStream.BeginRead(readBuffer, 0, READ_BUFFER_SIZE, AddressOf DoRead, Nothing)
Catch e As Exception
MarkAsDisconnected()
End Try
End Sub
Public Sub Connect()
Try
' The TcpClient is a subclass of Socket, providing higher level
' functionality like streaming.
client = New TcpClient("localhost", PORT_NUM)

' Start an asynchronous read invoking DoRead to avoid lagging the user
' interface.
client.GetStream.BeginRead(readBuffer, 0, READ_BUFFER_SIZE, AddressOf DoRead, Nothing)

' Make sure the window is showing before popping up connection dialog.

AttemptLogin()
DisplayText("Connected to server")
Catch Ex As Exception
DisplayText("ERROR: Server is not active. Please start server and try again.")
End Try
End Sub

' When the server disconnects, prevent further chat messages from being sent.
Public Sub MarkAsDisconnected()
Button2.Enabled = False
End Sub

' Process the command received from the server, and take appropriate action.
Public Sub ProcessCommands(ByVal strMessage As String)
Dim dataArray() As String

' Message parts are divided by "|" Break the string into an array accordingly.
dataArray = strMessage.Split(Chr(124))

' dataArray(0) is the command.
Select Case dataArray(0)
Case "JOIN"
' Server acknowledged login.
DisplayText("You have joined the chat" & Chr(13) & Chr(10))
Case "CHAT"
' Received chat message, display it.
DisplayText(dataArray(1) & Chr(13) & Chr(10))
Case "REFUSE"
' Server refused login with this user name, try to log in with another.
AttemptLogin()
Case "BROAD"
' Server sent a broadcast message
DisplayText("ServerMessage: " & dataArray(1) & Chr(13) & Chr(10))
End Select
End Sub

' Use a StreamWriter to send a message to server.
Public Sub SendData(ByVal data As String)
Dim writer As New IO.StreamWriter(client.GetStream)
writer.Write(data & vbCr)
writer.Flush()
End Sub