Accueil > > > CLASS TCP/IP LISTENER TRES SIMPLE ET MULTITHREAD DOTNET
CLASS TCP/IP LISTENER TRES SIMPLE ET MULTITHREAD DOTNET
Information sur la source
Description
C'est un de mes premiers code dotnet, soyez indulgent :) J'ai la fleme de poster le zip alors les plus motivés copie/colleront :p
Source
- Imports System.Threading
-
- Public Class clsListener
-
- Private intPort As Integer
- Private intMaxThreads As Integer
- Private intActiveThreads As Integer
- Private bListening As Boolean
- Private intTimeOut As Integer
- Private tcpListener As System.Net.Sockets.TcpListener
- Private WithEvents tmrListener As System.Windows.Forms.Timer
-
- Public Sub New()
- intPort = 6042 'A redéfinir
- intTimeOut = 3000
- intMaxThreads = 2
- tmrListener = New Windows.Forms.Timer()
- tmrListener.Enabled = False
- tmrListener.Interval = 100
- End Sub
-
- Public Property Listening() As Boolean
- Get
- Return bListening
- End Get
- Set(ByVal Value As Boolean)
- Dim ret As Boolean
- If Not (bListening) Then
- ret = Start_Listening()
- Else
- ret = Stop_Listening()
- End If
- If ret Then
- bListening = Not (bListening)
- End If
- End Set
- End Property
- Public Property Port() As Integer
- Get
- Return intPort
- End Get
- Set(ByVal Value As Integer)
- intPort = Value
- End Set
- End Property
- Public Property maxThreads() As Integer
- Get
- Return intMaxThreads
- End Get
- Set(ByVal Value As Integer)
- If Value > 0 Then
- intMaxThreads = Value
- End If
- End Set
- End Property
- Public Property TimeOut() As Integer
- Get
- Return intTimeOut
- End Get
- Set(ByVal Value As Integer)
- If Value > 0 Then
- intTimeOut = Value
- End If
- End Set
- End Property
- Public ReadOnly Property CurrentThreads() As Integer
- Get
- Return intActiveThreads
- End Get
- End Property
-
- Public Event PostMessage(ByVal dTimePosted As Date, ByVal strHost As String, ByVal rawMessage As String)
-
- Private Function Start_Listening() As Boolean
- Try
- If Not tcpListener Is Nothing Then
- tcpListener.Stop() 'Normalement inutile (dans un premier temps)
- Else
- tcpListener = New Net.Sockets.TcpListener(intPort)
- End If
- tcpListener.Start()
- tmrListener.Enabled = True
- Catch e As Exception
- Console.WriteLine(e.ToString)
- Return False
- End Try
- Return True
- End Function
- Private Function Stop_Listening() As Boolean
- Try
- If Not tcpListener Is Nothing Then
- tcpListener.Stop()
- End If
- tcpListener = Nothing
- Catch e As Exception
- Console.WriteLine(e.ToString)
- Return False
- End Try
- Return True
- End Function
-
- Private Sub GettingRawMessage(ByVal strHost As String, ByVal strMessage As String)
- RaiseEvent PostMessage(Now(), strHost, strMessage)
- End Sub
-
- Private Sub NewThread()
- intActiveThreads += 1
- End Sub
- Private Sub EndThread()
- intActiveThreads -= 1
- End Sub
-
- Private Sub tmrListener_Tick(ByVal sender As Object, ByVal e As System.EventArgs) Handles tmrListener.Tick
-
- Dim CurThreadStart As Threading.ThreadStart
- Dim CurThread As Threading.Thread
- Dim ThreadCount As Integer
- Dim i As Integer
-
- If Not (tcpListener.Pending()) Or (intActiveThreads >= intMaxThreads) Then
- Exit Sub
- End If
-
- tmrListener.Enabled = False
-
- Dim Connfollow As New clsFollowConn()
- Connfollow.tcpListener = tcpListener
- Connfollow.TimeOut = 5000
-
- AddHandler Connfollow.post_message, AddressOf GettingRawMessage
- AddHandler Connfollow.connect, AddressOf NewThread
- AddHandler Connfollow.disconnect, AddressOf EndThread
-
- CurThreadStart = New Threading.ThreadStart(AddressOf Connfollow.AcceptConnection)
- CurThread = New Threading.Thread(CurThreadStart)
- CurThread.Start()
-
- tmrListener.Enabled = True
-
- End Sub
-
- End Class
- Public Class clsFollowConn
-
- Private Declare Function GetTickCount Lib "kernel32" () As Integer
- Private intLastDataTime As Integer
- Private intTimeOut As Integer
- Private Const EoM = vbCrLf
- Public tcpListener As Net.Sockets.TcpListener
-
- Public Event disconnect()
- Public Event connect()
- Public Event post_message(ByVal host As String, ByVal message As String)
-
- Public Sub AcceptConnection()
-
- Dim CurThread As System.Threading.Thread
- Dim CurSocket As Net.Sockets.Socket
-
- Dim Buffer(1024) As Byte
- Dim Bytes As Integer
- Dim strTemp As String
- Dim bStop As Boolean
-
- RaiseEvent connect()
- CurThread = System.Threading.Thread.CurrentThread()
- CurSocket = tcpListener.AcceptSocket
-
- intLastDataTime = GetTickCount()
-
- While Not (bStop)
- If CurSocket.Available > 0 Then
- Bytes = CurSocket.Receive(Buffer, Buffer.Length, 0)
- If Bytes > 0 Then
- strTemp += System.Text.Encoding.Default.GetString(Buffer, 0, Bytes)
- split_msg(CType(CurSocket.RemoteEndPoint, Net.IPEndPoint).Address.ToString(), strTemp)
- intLastDataTime = GetTickCount()
- End If
- End If
- Application.DoEvents()
-
- If Not (CurSocket.Connected) Or ((GetTickCount() - intLastDataTime) > intTimeOut) Then
- CurSocket.Close()
- bStop = True
- End If
- End While
- RaiseEvent disconnect()
- End Sub
- Private Sub split_msg(ByVal strHost As String, ByRef strData As String)
- Dim lngPosLf, lngPosLast As Integer
- lngPosLast = 1
- lngPosLf = InStr(strData, EoM)
- While lngPosLf > 0
- RaiseEvent post_message(strHost, Mid$(strData, lngPosLast, lngPosLf - lngPosLast))
- lngPosLast = lngPosLf + Len(EoM)
- lngPosLf = InStr(lngPosLast, strData, EoM)
- End While
- strData = Right(strData, Len(strData) + 1 - lngPosLast)
- End Sub
-
- Public ReadOnly Property LastDataTime() As Integer
- Get
- Return intLastDataTime
- End Get
- End Property
- Public Property TimeOut() As Integer
- Get
- Return intTimeOut
- End Get
- Set(ByVal Value As Integer)
- intTimeOut = Value
- End Set
- End Property
-
- End Class
-
Imports System.Threading
Public Class clsListener
Private intPort As Integer
Private intMaxThreads As Integer
Private intActiveThreads As Integer
Private bListening As Boolean
Private intTimeOut As Integer
Private tcpListener As System.Net.Sockets.TcpListener
Private WithEvents tmrListener As System.Windows.Forms.Timer
Public Sub New()
intPort = 6042 'A redéfinir
intTimeOut = 3000
intMaxThreads = 2
tmrListener = New Windows.Forms.Timer()
tmrListener.Enabled = False
tmrListener.Interval = 100
End Sub
Public Property Listening() As Boolean
Get
Return bListening
End Get
Set(ByVal Value As Boolean)
Dim ret As Boolean
If Not (bListening) Then
ret = Start_Listening()
Else
ret = Stop_Listening()
End If
If ret Then
bListening = Not (bListening)
End If
End Set
End Property
Public Property Port() As Integer
Get
Return intPort
End Get
Set(ByVal Value As Integer)
intPort = Value
End Set
End Property
Public Property maxThreads() As Integer
Get
Return intMaxThreads
End Get
Set(ByVal Value As Integer)
If Value > 0 Then
intMaxThreads = Value
End If
End Set
End Property
Public Property TimeOut() As Integer
Get
Return intTimeOut
End Get
Set(ByVal Value As Integer)
If Value > 0 Then
intTimeOut = Value
End If
End Set
End Property
Public ReadOnly Property CurrentThreads() As Integer
Get
Return intActiveThreads
End Get
End Property
Public Event PostMessage(ByVal dTimePosted As Date, ByVal strHost As String, ByVal rawMessage As String)
Private Function Start_Listening() As Boolean
Try
If Not tcpListener Is Nothing Then
tcpListener.Stop() 'Normalement inutile (dans un premier temps)
Else
tcpListener = New Net.Sockets.TcpListener(intPort)
End If
tcpListener.Start()
tmrListener.Enabled = True
Catch e As Exception
Console.WriteLine(e.ToString)
Return False
End Try
Return True
End Function
Private Function Stop_Listening() As Boolean
Try
If Not tcpListener Is Nothing Then
tcpListener.Stop()
End If
tcpListener = Nothing
Catch e As Exception
Console.WriteLine(e.ToString)
Return False
End Try
Return True
End Function
Private Sub GettingRawMessage(ByVal strHost As String, ByVal strMessage As String)
RaiseEvent PostMessage(Now(), strHost, strMessage)
End Sub
Private Sub NewThread()
intActiveThreads += 1
End Sub
Private Sub EndThread()
intActiveThreads -= 1
End Sub
Private Sub tmrListener_Tick(ByVal sender As Object, ByVal e As System.EventArgs) Handles tmrListener.Tick
Dim CurThreadStart As Threading.ThreadStart
Dim CurThread As Threading.Thread
Dim ThreadCount As Integer
Dim i As Integer
If Not (tcpListener.Pending()) Or (intActiveThreads >= intMaxThreads) Then
Exit Sub
End If
tmrListener.Enabled = False
Dim Connfollow As New clsFollowConn()
Connfollow.tcpListener = tcpListener
Connfollow.TimeOut = 5000
AddHandler Connfollow.post_message, AddressOf GettingRawMessage
AddHandler Connfollow.connect, AddressOf NewThread
AddHandler Connfollow.disconnect, AddressOf EndThread
CurThreadStart = New Threading.ThreadStart(AddressOf Connfollow.AcceptConnection)
CurThread = New Threading.Thread(CurThreadStart)
CurThread.Start()
tmrListener.Enabled = True
End Sub
End Class
Public Class clsFollowConn
Private Declare Function GetTickCount Lib "kernel32" () As Integer
Private intLastDataTime As Integer
Private intTimeOut As Integer
Private Const EoM = vbCrLf
Public tcpListener As Net.Sockets.TcpListener
Public Event disconnect()
Public Event connect()
Public Event post_message(ByVal host As String, ByVal message As String)
Public Sub AcceptConnection()
Dim CurThread As System.Threading.Thread
Dim CurSocket As Net.Sockets.Socket
Dim Buffer(1024) As Byte
Dim Bytes As Integer
Dim strTemp As String
Dim bStop As Boolean
RaiseEvent connect()
CurThread = System.Threading.Thread.CurrentThread()
CurSocket = tcpListener.AcceptSocket
intLastDataTime = GetTickCount()
While Not (bStop)
If CurSocket.Available > 0 Then
Bytes = CurSocket.Receive(Buffer, Buffer.Length, 0)
If Bytes > 0 Then
strTemp += System.Text.Encoding.Default.GetString(Buffer, 0, Bytes)
split_msg(CType(CurSocket.RemoteEndPoint, Net.IPEndPoint).Address.ToString(), strTemp)
intLastDataTime = GetTickCount()
End If
End If
Application.DoEvents()
If Not (CurSocket.Connected) Or ((GetTickCount() - intLastDataTime) > intTimeOut) Then
CurSocket.Close()
bStop = True
End If
End While
RaiseEvent disconnect()
End Sub
Private Sub split_msg(ByVal strHost As String, ByRef strData As String)
Dim lngPosLf, lngPosLast As Integer
lngPosLast = 1
lngPosLf = InStr(strData, EoM)
While lngPosLf > 0
RaiseEvent post_message(strHost, Mid$(strData, lngPosLast, lngPosLf - lngPosLast))
lngPosLast = lngPosLf + Len(EoM)
lngPosLf = InStr(lngPosLast, strData, EoM)
End While
strData = Right(strData, Len(strData) + 1 - lngPosLast)
End Sub
Public ReadOnly Property LastDataTime() As Integer
Get
Return intLastDataTime
End Get
End Property
Public Property TimeOut() As Integer
Get
Return intTimeOut
End Get
Set(ByVal Value As Integer)
intTimeOut = Value
End Set
End Property
End Class
Conclusion
Initialisation & Reception de "message" :
Private WithEvents myListener As clsListener
myListener = New clsListener() myListener.Listening = True
Private Sub myListener_PostMessage(ByVal dTimePosted As Date, ByVal strHost As String, ByVal rawMessage As String) Handles myListener.PostMessage MsgBox("Date : " & CStr(dTimePosted) & vbCrLf & "Host : " & strHost & vbCrLf & "Message : " & rawMessage) End Sub
Sources du même auteur
Sources de la même categorie
Commentaires et avis
Discussions en rapport avec ce code source dans le forum
[VB.NET]Socket [ par shadow1779 ]
j'ai vu un bon tuto sur les sockets en VB.NET cependant je me pose quelques questions,déja comment savoir si je suis vraiment connecté au so
[vb.net] echange de données en multithread [ par Lucyberad ]
salut vbfrancien, vbfrancienne (c possible ^^) j'ai depuis peu essayé de faire du multithread afin de lancer une requete internet. jusque la auc
ACCES SOCKET PAR AUTRE THREAD [ par Ant95 ]
Bonsoir à tous, J'ai un problème sur un projet de chat qui utilise les sockets. En fait j'aimerais que chaque serveur socket soit créé sur un thread
Probleme de thread avec lecture du port COM [VB2010] [ par matheonimbus30 ]
Bonjour, J'ai créé un projet pour lire le port usb, avec une carte arduino branchée, cette carte envoie des données (0 ou 1)par le port usb, je réussi
Les sockets [ par boomer901 ]
Hello, Je souhaite créer un programme qui surveille un compte dofus, quand on ne joue plus on le lance, si le compte se connecte, c'est qu'il y a ten
Sockets sans Port forwarding?? (hole punching?) [ par MiharbiDoNo ]
bonjour, je voulais faire une application connectant deux ordi à traver un reseau, avec un TCPClient et un TCPlistener aucun probleme (ou bien les so
Vb.net Multithread [ par rsx602 ]
Bonjours , je fais présentement un program qui utilise le multithread seulement mon problème est que une fois mon "private sub fonction()" j'aimerais
Multi Thread sur pages MDI : Besoin d'aide ! [ par guilleto ]
Bonjour à toutes et tous, J'ai actuellement une application qui fonctionne avec une page MDI Parent et (pour l'instant) 3 feuilles MDI filles, dans c
arreter l'exécutuion d'un thread [ par Taur33 ]
Bonsoir à tous Voila mon probleme : j'ai un userform avec un bouton pour le minimized Quand je place la souris (je dis bien je place pas je click)sur
|
Derniers Blogs
XNA IS DEAD!XNA IS DEAD! par richardc
Depuis la semaine dernière (et grâce aux TechDays 2012), je me penche activement sur la nouvelle version de Windows, aka Windows 8. Vous me direz, il était temps puisque la première preview date de Septembre dernier.
OK. Remarquez, on n'en est qu'aux...
Cliquez pour lire la suite de l'article par richardc TECHDAYS PARIS 2012 : WINDOWS SERVER "8" QUOI DE 9 !TECHDAYS PARIS 2012 : WINDOWS SERVER "8" QUOI DE 9 ! par ROMELARD Fabrice
Speakers: Fabrice Meillon et Stanislas Quastana Cette session est basée entièrement sur celle donnée lors de la BUILD cet hiver. Il n'y a pas d'ajout d'information en rapport avec cet évènement passé. Windows 8 Server sera intégralem...
Cliquez pour lire la suite de l'article par ROMELARD Fabrice [HTML5] AUTOUR DU W3C : NOUVEAUX STANDARDS ET WEB MOBILE (LILLE)[HTML5] AUTOUR DU W3C : NOUVEAUX STANDARDS ET WEB MOBILE (LILLE) par Gio
Je m'y prends un peu tard je sais, mais bon je suis développeur web et donc hyper fainéant ! Toujours dans le cadre des technologies émergentes, ici HTML5, parce qu'on aime HTML5 chez Wyg , nous seront présent, le vieux ( Aurélien V.) et moi, pour pr...
Cliquez pour lire la suite de l'article par Gio [WP7] DYNAMICALLY CHANGE STARTUP PAGE[WP7] DYNAMICALLY CHANGE STARTUP PAGE par KooKiz
Let's say that you want to allow the user to customize the startup page of your application. You can easily change the startup page by editing the 'NavigationPage' attribute in the manifest file. But the manifest cannot be modified once the applicatio...
Cliquez pour lire la suite de l'article par KooKiz
Logiciels
DocTranslate (V3.1.0.0)DOCTRANSLATE (V3.1.0.0)DocTranslate est un traducteur de document Microsoft Word, PowerPoint et Excel. Il permet d'autom... Cliquez pour télécharger DocTranslate Tribler (2012)TRIBLER (2012)Tribler est un client pair à pair (P2P/Peer-to-Peer) open source avec la capacité de regarder des... Cliquez pour télécharger Tribler OneSwarm (2012)ONESWARM (2012)Le peer-to-peer qui protège votre vie privée, c'est OneSwarm.
Ce logiciel de peer-to-peer crypté... Cliquez pour télécharger OneSwarm PONAMEDIA PREMIUM - HELLLOOO FLASH DEMO (V8.4)PONAMEDIA PREMIUM - HELLLOOO FLASH DEMO (V8.4)PONAMEDIA TV DEVIENS HELLLOOO FLASH
LA TV SUR VOTRE ORDINATEUR.
Toute une plateforme Multi... Cliquez pour télécharger PONAMEDIA PREMIUM - HELLLOOO FLASH DEMO Academy System (17.2.1.0)ACADEMY SYSTEM (17.2.1.0)Logiciel de gestion des établissements.
- élèves/étudiants (inscription, dossier, absence...)
-... Cliquez pour télécharger Academy System
|