Advertisement
LaPanthere

MultiClientTCPServerSocket Class

Jun 4th, 2013
290
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
VB.NET 9.52 KB | None | 0 0
  1. Imports System.Net.Sockets
  2. Imports System.Net
  3. Namespace MultiClientTCPServerSocket
  4.  
  5.     'Author:    LaPanthere
  6.     'Date:      4th of June, 2013
  7.     'Desc:      A simple class with event calling that will run multiple clients. Store the clients in a list of sockets if you wish to do stuff with them.
  8.     'Credits:   None, based off my own work with async sockets.
  9.  
  10.     Public Class MultiClientTCPSeverSocket
  11.         Public Event MessageReceived As MessageReceivedEventHandler
  12.         Public Event ClientConnected As ClientConnectedEventHandler
  13.         Public Event ClientDisconnected As ClientDisconnectedEventHandler
  14.         Dim clientSocket As Socket
  15.         Dim serverSocket As Socket
  16.         Dim port As String
  17.         Dim byteSize(66291456) As Byte
  18.         Dim IpEndPoint As Net.IPEndPoint
  19.  
  20.         Public Delegate Sub MessageReceivedEventHandler(ByVal sender As Object, ByVal e As MessageReceivedEventArgs)
  21.         Public Delegate Sub ClientConnectedEventHandler(ByVal sender As Object, ByVal e As ClientConnectedEventArgs)
  22.         Public Delegate Sub ClientDisconnectedEventHandler(ByVal sender As Object, ByVal e As ClientDisconnectedEventArgs)
  23.  
  24.         ''' <summary>
  25.         ''' Creates a new Multiple client server socket
  26.         ''' </summary>
  27.         ''' <param name="port">The port to listen for clients</param>
  28.         ''' <param name="buffer">The buffer for messages</param>
  29.         ''' <remarks></remarks>
  30.         Public Sub New(ByVal port As String, Optional ByVal buffer() As Byte = Nothing)
  31.             'General defining of existing strings/related
  32.             Me.port = port
  33.             If Not IsNothing(buffer) Then
  34.                 Me.byteSize = buffer
  35.             End If
  36.         End Sub
  37.  
  38.         ''' <summary>
  39.         ''' Starts the server with the specified data (define a new instance to use this method)
  40.         ''' </summary>
  41.         ''' <returns></returns>
  42.         ''' <remarks></remarks>
  43.         Public Function StartServer() As Boolean
  44.             Try
  45.                 'Define what the server socket really is
  46.                 serverSocket = New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
  47.  
  48.                 'Create a local IP endpoint
  49.                 IpEndPoint = New Net.IPEndPoint(IPAddress.Any, Me.port)
  50.  
  51.                 'Create the local endpoint ip bind
  52.                 serverSocket.Bind(IpEndPoint)
  53.  
  54.                 'Allow several thousand clients to be backlogged
  55.                 serverSocket.Listen(500000)
  56.  
  57.                 'Start accepting clients through the socket
  58.                 serverSocket.BeginAccept(New AsyncCallback(AddressOf OnClientAccept), Nothing)
  59.                 Return True
  60.             Catch
  61.                 Return False
  62.             End Try
  63.         End Function
  64.  
  65.         ''' <summary>
  66.         ''' Attempts to close the server socket and end all connecting clients
  67.         ''' </summary>
  68.         ''' <param name="timeout">The time before closing the socket</param>
  69.         ''' <returns></returns>
  70.         ''' <remarks></remarks>
  71.         Public Function CloseServer(Optional ByVal timeout As Integer = 1) As Boolean
  72.             Try
  73.                 serverSocket.Close(timeout)
  74.                 Return True
  75.             Catch
  76.                 Return False
  77.             End Try
  78.         End Function
  79.         Public Function DisconnectClient(ByVal client As Socket) As Boolean
  80.             Try
  81.                 'Begin disconnecting a client and assign its async call back to OnClientDisconnect
  82.                 client.BeginDisconnect(False, New AsyncCallback(AddressOf OnClientDisconnect), client)
  83.                 Return True
  84.             Catch
  85.                 Return False
  86.             End Try
  87.         End Function
  88.  
  89.  
  90.         ''' <summary>
  91.         ''' Sends a message asynchronously to the client socket specified
  92.         ''' </summary>
  93.         ''' <param name="message">The message you wish to send</param>
  94.         ''' <param name="client">The socket that you wish to send the message to, can be grabbed from most events</param>
  95.         ''' <returns></returns>
  96.         ''' <remarks></remarks>
  97.         Public Function SendMessage(ByVal message As String, ByVal client As Socket) As Boolean
  98.             Try
  99.                 'Define bytes to send by getting the bytes from the message string
  100.                 Dim sendBytes As Byte() = System.Text.ASCIIEncoding.ASCII.GetBytes(message)
  101.  
  102.                 'Begin sending data and assign the async callback to OnMesssageSent
  103.                 client.BeginSend(sendBytes, 0, sendBytes.Length, SocketFlags.None, New AsyncCallback(AddressOf OnMessageSent), client)
  104.  
  105.                 Return True
  106.             Catch
  107.                 Return False
  108.             End Try
  109.         End Function
  110.  
  111.         Private Sub OnClientAccept(ByVal asyncres As IAsyncResult)
  112.             Try
  113.                 'End accepting client and restart client acceptance
  114.                 clientSocket = serverSocket.EndAccept(asyncres)
  115.                 serverSocket.BeginAccept(New AsyncCallback(AddressOf OnClientAccept), Nothing)
  116.  
  117.                 'Raise a new event letting the user know that a client has connected
  118.                 Dim e As New ClientConnectedEventArgs
  119.                 e.clientID = clientSocket.Handle.ToString
  120.                 e.clientSocket = clientSocket
  121.                 RaiseEvent ClientConnected(Me, e)
  122.  
  123.                 'Start receiving messages from the client
  124.                 clientSocket.BeginReceive(byteSize, 0, byteSize.Length, SocketFlags.None, New AsyncCallback(AddressOf OnMessageReceive), clientSocket)
  125.  
  126.                 'Begin constant check to see whether the client is still connected
  127.             Catch ex As Exception
  128.                 'If error occurs, throw a new exception
  129.                 Throw New Exception("Failed to accept a client. See 'OnClientAccept' Sub. Details: " & ex.Message)
  130.             End Try
  131.         End Sub
  132.  
  133.         Private Sub OnMessageReceive(ByVal asyncres As IAsyncResult)
  134.             Try
  135.                 'Create a socket to use with events
  136.                 Dim client As Socket = asyncres.AsyncState
  137.  
  138.                 'If the client is not connected break and dispose the client
  139.                 If client.Connected = False And client.Poll(2000, SelectMode.SelectRead) Then
  140.                     Exit Sub
  141.                 End If
  142.  
  143.                 'Create a byte from the byteSize and set it to the message from the client
  144.                 Dim bytesRec As Byte() = byteSize
  145.                 Dim message As String = System.Text.ASCIIEncoding.ASCII.GetString(bytesRec).Trim()
  146.  
  147.                 'Raise the MessageReceived Event with parameters specified above
  148.                 Dim e As New MessageReceivedEventArgs
  149.                 e.Sender = client.Handle.ToString
  150.                 e.Message = message
  151.                 e.clientSocket = client
  152.                 RaiseEvent MessageReceived(Me, e)
  153.                 'Start recieving data from the socket again
  154.                 clientSocket.BeginReceive(byteSize, 0, byteSize.Length, SocketFlags.None, New AsyncCallback(AddressOf OnMessageReceive), clientSocket)
  155.             Catch
  156.                 'If error occurs, throw a new exception
  157.                 Throw New Exception("Failed to receive message from client or related")
  158.             End Try
  159.         End Sub
  160.  
  161.         Private Sub OnMessageSent(ByVal asyncres As IAsyncResult)
  162.             Try
  163.                 Dim client As Socket = asyncres.AsyncState
  164.  
  165.                 'Gracefully let the message sending be ended
  166.                 client.EndSend(asyncres)
  167.             Catch
  168.                 'If error occurs, throw a new exception
  169.                 Throw New Exception("Failed to disconnect client")
  170.             End Try
  171.         End Sub
  172.  
  173.         Private Sub OnClientDisconnect(ByVal asyncres As IAsyncResult)
  174.             Try
  175.                 'Define a socket and use it for the events, setting it to the asyncstate of the result
  176.                 Dim client As Socket = asyncres.AsyncState
  177.  
  178.                 'Raise a new clientdisconnected event
  179.                 Dim e As New ClientDisconnectedEventArgs
  180.                 e.clientID = client.Handle.ToString
  181.                 e.clientSocket = client
  182.                 RaiseEvent ClientDisconnected(Me, e)
  183.  
  184.                 'End the disconnect sequence
  185.                 client.EndDisconnect(asyncres)
  186.             Catch
  187.                 'If error occurs, throw a new exception
  188.                 Throw New Exception("Failed to disconnect client")
  189.             End Try
  190.         End Sub
  191.  
  192.         ''' <summary>
  193.         ''' Checks whether a socket is alive by polling it
  194.         ''' </summary>
  195.         ''' <param name="socket">The socket you wish to check</param>
  196.         ''' <returns></returns>
  197.         ''' <remarks></remarks>
  198.         Public Function IsConnected(ByVal socket As Socket) As Boolean
  199.             Try
  200.                 'Check whether socket is alive by polling it.
  201.                 Return Not (socket.Poll(1, SelectMode.SelectRead) AndAlso socket.Available = 0)
  202.             Catch ex As SocketException
  203.                 Return False
  204.             End Try
  205.         End Function
  206.     End Class
  207.  
  208.     Public Class MessageReceivedEventArgs
  209.         Inherits EventArgs
  210.         Public Sender As String
  211.         Public clientSocket As Socket
  212.         Public Message As String
  213.     End Class
  214.  
  215.     Public Class ClientConnectedEventArgs
  216.         Inherits EventArgs
  217.         Public clientID As String
  218.         Public clientSocket As Socket
  219.     End Class
  220.  
  221.     Public Class ClientDisconnectedEventArgs
  222.         Inherits EventArgs
  223.         Public clientID As String
  224.         Public clientSocket As Socket
  225.     End Class
  226. End Namespace
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement