Hello There, Guest!
View New Posts  |  View Today's Posts
[VB.Net] Multi-Client Server Async Socket Example

ii 
  • 4 Vote(s) - 4.5 Average


08-22-2012, 12:40 AM #61
BANNY_HAIZER
Junior Member
**
Posts: 1 Threads:0 Joined: Aug 2012 Reputation: 0

RE: Multi-Client Server Async Socket Example
[Content Removed]
This post was last modified: 08-22-2012, 01:11 AM by AceInfinity.

08-22-2012, 01:12 AM #62
AceInfinity
Developer
*******
Administrators
Posts: 9,733 Threads:1,026 Joined: Jun 2011 Reputation: 76

RE: Multi-Client Server Async Socket Example
@BANNY_HAIZER - This is an English only forum please. I don't want posts that nobody can read here, they just spam the community.
This post was last modified: 08-22-2012, 01:12 AM by AceInfinity.


Microsoft MVP .NET Programming - (2012 - Present)
®Crestron DMC-T Certified Automation Programmer

Development Site: aceinfinity.net

 ▲
 ▲ ▲

08-30-2012, 12:57 PM #63
CarlaSexy
Junior Member
**
Posts: 1 Threads:0 Joined: Aug 2012 Reputation: 0

RE: Multi-Client Server Async Socket Example
(06-08-2011, 01:47 AM)KoBE Wrote:  Great Nicethread

09-06-2012, 01:25 AM #64
vichien789
Junior Member
**
Posts: 4 Threads:3 Joined: Aug 2012 Reputation: 0

RE: Multi-Client Server Async Socket Example
Why you request a lot of posting

09-06-2012, 07:15 PM #65
AceInfinity
Developer
*******
Administrators
Posts: 9,733 Threads:1,026 Joined: Jun 2011 Reputation: 76

RE: Multi-Client Server Async Socket Example
(09-06-2012, 01:25 AM)vichien789 Wrote:  Why you request a lot of posting

We had the limit to a lower number before and it just encouraged people to spam very low quality posts. Nobody cared to have the decency to not spam to get what they wanted, so it was increased.

Originally we had no requirement, but figured that we had too many people signing up and downloading or just downloading content when we had it available for guests. I think it's more than fair to have people give back to the community for others efforts. Based on what was seen in the past though, this "high" number was a result of others that have spammed here out of discourtesy and which you can blame :)

I don't have any idea why people don't see my announcement on the board index though after they register. It's at the very top and in nice red text... Unsure

http://tech.reboot.pro/showthread.php?tid=1861


Microsoft MVP .NET Programming - (2012 - Present)
®Crestron DMC-T Certified Automation Programmer

Development Site: aceinfinity.net

 ▲
 ▲ ▲

09-07-2012, 02:25 AM #66
yfzpurgatory
Junior Member
**
Posts: 10 Threads:0 Joined: Sep 2012 Reputation: 0

RE: Multi-Client Server Async Socket Example
Alright, so .NET and OOP is pretty foreign to me. I'm pretty handy in VB6 and PHP, but moving over to VB 2010 has got me all sorts of messed up. So here's the problem:

I'm trying to diversify your idea of sending a message to all connected clients by use of a listview menu, and instead having a text box to type a message into and a "send" button to send it. I've kept the listview and the storing of the client information in the tag property. I created an integer named "Connected" to keep track of how many people were connected to the server; this is used in a loop as an index for the array that stores the pertinent client information.

Here's the loop:

PHP Code:
Dim i As Integer Connected
        
While 0
            SendToAll
(txtBroadcast.TextClientsConnected(i))
            
1
        End 
While 

An error occurs when a client connects on this line:

PHP Code:
Dim lvi As New ListViewItem(Client.LocalEndPoint.ToString)
        
lvi.Tag Client
        ClientsConnected
(Connected) = Client
        lsvClients
.Items.Add(lvi

It says that a new instance of the object must be created. Now, I've already made it clear that I'm no wizard when it comes to object-oriented programming, so I'm not too clear on what I should do to store the information I need to loop through an array of clients and send information to either 1 pre-determined client or all of them.

Your help is greatly appreciated, and thank you in advance.
This post was last modified: 09-07-2012, 02:29 AM by yfzpurgatory.

09-07-2012, 11:53 AM #67
KoBE
¯\_(ツ)_/¯
******
Global Moderators
Posts: 4,862 Threads:494 Joined: Jun 2011 Reputation: 67

RE: Multi-Client Server Async Socket Example
Why not loop through the ListView?

Code:
For each lvi as ListViewItem In lsvClients

    Send("Message from server", lvi.Tag)

Next

09-07-2012, 12:51 PM #68
yfzpurgatory
Junior Member
**
Posts: 10 Threads:0 Joined: Sep 2012 Reputation: 0

RE: Multi-Client Server Async Socket Example
Well, in VB6 we would loop through each lsvClients.Items().Tag, but since we can no longer index (object not set as an instance), I'm totally stumped. Once again, I'm no OOP wizard. lol.

Thanks for the help. I'll edit this if I have any more trouble.

Edit:
Code:
For each lvi as ListViewItem In lsvClients

    Send("Message from server", lvi.Tag)

Next

For each lvi as ListViewItem In lsvClients, there is an error here. Expression is of type ListViewItem and not a collection. Wouldn't we use "lsvClients.Items" since that is the collection? Just guessing here. So much has changed.

Edit2:
Alright, I got it to work but there's another problem. The Client closes automatically once it has received the message. Looking through the code now, but there is no Close() or Kill command for the form as I typed it manually instead of cp'ing.

Here's the code. It should me exactly how you have it aside from me having to use "System.AsyncCallback" instead of just "AsyncCallback". I'm using VB 2010 Express, so that may be why. As for the automatic closing of the program after a message has been received, no clue:

Code:
Imports System.Net, System.Net.Sockets

Public Class frmClient
    Dim sckClient As Socket
    Dim byteData(1023) As Byte

    Private Sub ConnectToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles ConnectToolStripMenuItem.Click
        sckClient = New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
        Dim IpAddress As IPAddress = IpAddress.Parse("127.0.0.1")
        Dim IpEndPoint As IPEndPoint = New IPEndPoint(IPAddress, 8800)

        sckClient.BeginConnect(IpEndPoint, New System.AsyncCallback(AddressOf OnConnect), Nothing)
    End Sub

    Private Sub OnConnect(ByVal ar As IAsyncResult)
        sckClient.EndConnect(ar)
        sckClient.BeginReceive(byteData, 0, byteData.Length, SocketFlags.None, _
                               New System.AsyncCallback(AddressOf OnReceive), sckClient)
    End Sub

    Private Sub OnReceive(ByVal ar As IAsyncResult)
        Dim Client As Socket = ar.AsyncState
        Client.EndReceive(ar)
        Dim bytesRec As Byte() = byteData
        Dim Msg As String = System.Text.ASCIIEncoding.ASCII.GetString(bytesRec)
        Read(Msg)
        sckClient.BeginReceive(byteData, 0, byteData.Length, SocketFlags.None, _
                               New System.AsyncCallback(AddressOf OnReceive), sckClient)
    End Sub

    Delegate Sub _Read(ByVal msg As String)

    Private Sub Read(ByVal msg As String)
        If InvokeRequired Then
            Invoke(New _Read(AddressOf Read), msg)
        End If

        rtbChat.Text = rtbChat.Text & vbCrLf & msg
    End Sub
End Class

Edit3:
So I built the solution and ran the executable's instead of running them from the designer. The clients do not close automatically when ran this way. However, Houston, we have another issue. It looks like the message is being duplicated, so instead of receiving one line from the server, "Message from the Server", we are receiving:

"Message from the Server"
"Message from the Server".

Edit4:
Fixed the duplicate message issue. I was missing "Exit Sub" after invoking the delegate for Read. Also fixed another bug that caused partial duplicate messages on this line:

Code:
Private Sub Read(ByVal msg As String)
        If InvokeRequired Then
            Invoke(New _Read(AddressOf Read), msg)
            Exit Sub
        End If

         rtbChat.Text = rtbChat.Text & vbCrLf & msg.Trim
    End Sub

Changed it to this and it works flawlessly aside from the first line being blank due to the vbCrLf. I tried to use vbCrLf at the end of the line but it doesn't seem to work:

Code:
Private Sub Read(ByVal msg As String)
        If InvokeRequired Then
            Invoke(New _Read(AddressOf Read), msg)
            Exit Sub
        Else
            rtbChat.Text = rtbChat.Text & vbCrLf & msg.Trim
        End If
    End Sub

So I was able to get the text to display without the blank line from the first message received. A little sloppy and there's probably a better, simpler way to do it, but:

Code:
rtbChat.Text = rtbChat.Text & vbCrLf & msg.Trim
rtbChat.Text = rtbChat.Text.Trim

Moving on to delimiters now. Trying to get broadcasted server messages to show like this:

"Server: message here", with the message text being black and "Server:" being blue.
This post was last modified: 09-07-2012, 02:01 PM by yfzpurgatory.

09-07-2012, 02:42 PM #69
KoBE
¯\_(ツ)_/¯
******
Global Moderators
Posts: 4,862 Threads:494 Joined: Jun 2011 Reputation: 67

RE: Multi-Client Server Async Socket Example
Since these methods are async they are running multi threaded.. so when an exception occurs, I think it just exits the thread.

In all honesty.. I think you'd be better off using a TcpClient which basically is a wrapper for the Socket class. I don't remember WinSock much but I think it's similar to that.

Let me whip together an easier example that will be easier for you to grasp. Then once you get the concept down, it will be easier for you to move on to a more advanced concept.

I'll reply to this thread when I get something thrown together.

09-07-2012, 02:52 PM #70
yfzpurgatory
Junior Member
**
Posts: 10 Threads:0 Joined: Sep 2012 Reputation: 0

RE: Multi-Client Server Async Socket Example
(09-07-2012, 02:42 PM)KoBE Wrote:  Since these methods are async they are running multi threaded.. so when an exception occurs, I think it just exits the thread.

In all honesty.. I think you'd be better off using a TcpClient which basically is a wrapper for the Socket class. I don't remember WinSock much but I think it's similar to that.

Let me whip together an easier example that will be easier for you to grasp. Then once you get the concept down, it will be easier for you to move on to a more advanced concept.

I'll reply to this thread when I get something thrown together.
I appreciate it. I've actually got everything working pretty smoothly. I edited my original post to keep from spamming the thread. I'm working on delimiters now, but the safest delimiters that I know of (ê and the like) are being scrambled due to the ASCII encoding and refuse to work. Simple delimiters such as | and @ work fine, but as a safety precaution I do not want a user to type something and cause a truncated message due to them using the delimiter. Here's what I have so far:

The sorting function that I placed in a module so the form would be clean:
Code:
Module sckWoker    
Public Function sortDelim(ByVal msg As String)        
     Dim tempData() As String = msg.Split("")
     Select Case tempData(0).Trim            
     Case "SERVERMSG"                
          Return "Server: " & tempData(1).Trim            
     Case "CLIENTMSG"                
          Return "Client: " & tempData(1).Trim        
     End Select
    
     Return "No Message. Error."    
End Function
End Module

Like I said, this works just fine but there are 2 problems. 1) ASCII encoding/decoding scrambles the delimiter and creates a "No Message. Error" return. 2) Using tempData = msg.Split("") only allows for ONE delimiter. I tried used a string such as "!$#@", which is something a normal person would never type, but split only uses one character in the string and returns the rest in the message. You'd get something like, "Server: $#@messagehere".

Here's the line where the function is called:
Code:
Dim Msg As String = System.Text.ASCIIEncoding.ASCII.GetString(bytesRec)
        Read(sortDelim(Msg))        
        sckClient.BeginReceive(byteData, 0, byteData.Length, SocketFlags.None, _                              
                                              New System.AsyncCallback(AddressOf OnReceive), sckClient)

Alright, so now the newest problem is the messages contain truncated segments of the last message sent. Is there any way to clear the pipe after its been received so that this doesn't happen? Here's an example of what I'm referring to:

First Message Sent: "Hi All"
First Message Received: "Hi All"

Second Message Sent: "Wassup"
Second Message Received: "Hi AllWassup"

It seems to clear over time. If I wait 5-10 seconds before sending another message, it will not do this.

Edit:
After reviewing the flow of sending operations, I found a possible error that is causing the stream to not be closed properly:

Code:
Private Sub SendToAll(ByVal msg As String, ByVal Client As Socket)
        Dim sendBytes As Byte() = System.Text.ASCIIEncoding.ASCII.GetBytes(msg)
        Client.BeginSend(sendBytes, 0, sendBytes.Length, SocketFlags.None, New System.AsyncCallback(AddressOf OnSend), Client)
    End Sub

    Private Sub OnSend(ByVal ar As System.IAsyncResult)
        Dim Client As Socket = ar.AsyncState
        Client.EndSend(ar)
    End Sub

On this line, "Client.BeginSend(sendBytes, 0, sendBytes.Length, SocketFlags.None, New System.AsyncCallback(AddressOf OnSend), Client)", you'll notice that OnSend requires a variable to be passed through it; the "ByVal ar as System.IAsyncResult". In the BeginSend line, nothing is being passed so when we get to "Client.EndSend(ar)", it's practically doing nothing. I have no idea what to pass as I don't know what "ar" stands for. Just thought I'd bring it up.
This post was last modified: 09-07-2012, 03:06 PM by yfzpurgatory.


ii 


Forum Jump:


Possibly Related Threads...
Thread Author Replies Views Last Post
Exclamation  problem multi post + httpwebrequest read ip sharokurdi 1 1,399 11-11-2016, 06:39 PM
Last Post: AceInfinity
   Create your own IRC Client [C#/VB.Net] KoBE 185 125,099 10-01-2016, 06:57 PM
Last Post: AceInfinity
   IRC Client Class KoBE 110 77,657 10-01-2016, 06:52 PM
Last Post: AceInfinity
  Telnet Client AceInfinity 5 2,995 06-05-2016, 07:48 PM
Last Post: AceInfinity
   Twitch chat bot (irc client) dmgvol 11 19,795 08-24-2015, 11:59 PM
Last Post: Signal_20


Users browsing this thread: 1 Guest(s)