begin process at 2012 02 14 03:43:21
  Trouver un code source :
 
dans
 
Accueil > 

Code

 > 

Réseau & Internet

 > CLASS TCP/IP LISTENER TRES SIMPLE ET MULTITHREAD DOTNET

CLASS TCP/IP LISTENER TRES SIMPLE ET MULTITHREAD DOTNET


 Information sur la source

Note :
7 / 10 - par 3 personnes
7,00 / 10

  • 1

  • 2

  • 3

  • 4

  • 5

  • 6

  • 7

  • 8

  • 9

  • 10
Catégorie :Réseau & Internet Source .NET ( DotNet ) Classé sous :tcpip, multithread, tcplistener, thread, sockets Niveau :Débutant Date de création :13/08/2002 Date de mise à jour :13/08/2002 14:45:48 Vu :20 655

Auteur : zappy

Ecrire un message privé
Site perso
Ce membre participe au partage de revenus publicitaires
Commentaire sur cette source (9)
Ajouter un commentaire et/ou une note


 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

Source avec Zip EASY ARRAY, LES TABLEAUX DYNAMIQUES FACILE !
CLASS CONNEXION ADODB SECURISE
Source avec Zip CRACK DE "PROTECTION INVIOLABLE PAR MOT DE PASSE"
Source avec Zip MAGIQUE CAPTURE (CAPTURE D'ÉCRAN ET DE SOUS FENÊTRES)
TRAITER UNE LIGNE CSV

 Sources de la même categorie

Source avec Zip Source avec une capture GESTIONNAIRE DE TÉLÉCHARGEMENT, AVEC REPRISE ET MULTITHREADI... par Madx23
Source avec Zip Source avec une capture CONVERTIR DU TEXTE RTF EN CODE HTML ET VICE-VERSA par vicosta
Source avec Zip Source avec une capture DICTIONAIRE TEXT/AUDIO/VISUELLE ANGLAIS AVEC WEBBROWSER CONT... par majnounmajda
Source avec Zip Source .NET (Dotnet) NSLOOKUP EN VB.NET OU COMMENT FAIRE UNE REQÛETE DNS EN PRÉCI... par ShareVB
Source avec Zip Source avec une capture MINI SEVEUR HTTP AVEC INTERFACE GRAPHIQUE ET IMPLÉMENTATIONS... par lemout

 Sources en rapport avec celle ci

Source avec Zip Source .NET (Dotnet) [VB.NET 2008] EXECUTION MULTITHREAD DE PLUSIEURS FONCTION À ... par ShadowTzu
Source avec Zip Source .NET (Dotnet) MULTI THREAD AVEC AFFICHAGE par jaknight007
Source avec Zip Source avec une capture AFFINITÉ DES PROCESSUS ET DES THREADS par draluorg
Source avec Zip EXEMPLE D'APPLICATION MULTITHREAD par thel0rd
Source avec Zip Source .NET (Dotnet) PATRON SINGLETON (AVEC PROTECTION CONTRE LES MULTI THREAD), ... par dragon

Commentaires et avis

Commentaire de Bodekaer le 09/12/2002 11:19:42

Hi,

I am currently using your code in a VB.NET app I have created.

But when ever a thread is runinng, the loop that checks for new messages, uses a lot of CPU.
I actually thought that the Application.Doevents, would prevent the code from using a lot of CPU. But it doesn't.

I am sure it although wont affect the performance of other programs, but it looks "wild" the my program looks like it is using 100% of the CPU (and I am using a 2.5 Ghz machine :)

Is there anything to do to prevent this ?

/Michael

Commentaire de zappy le 09/12/2002 11:31:24

Hi bodekaer,

I'm sorry, now i'm coding in C# and not in VB.NET.

You can use asynchronous sockets for betters performances without multi-threading (one thread / session is not good for a lot connections).

I have tested this code on my win2k : works with 5 connections without problem.

Happy coding !

ps: Sorry for my bad english :)

Commentaire de Bodekaer le 12/12/2002 11:45:49

No problem, my french isn't that good either :)

Well, I was wondering if you had a good example of hw to use asynchronous sockets in VB.NET

My program will normally handle between 30-90 connections at the same time.

/Michael

Commentaire de zappy le 12/12/2002 11:51:03

I haven't that in VB.NET.

But i have a good link for C# programming sockets in a non-blocking mode.
http://www.codeproject.com/csharp/socketsincs.asp

Happy coding !

Commentaire de RayBan le 05/03/2003 20:51:21

Hi,

I am not sure, but there a TCPListener class in .Net, that do all the thing your code do...

Commentaire de zappy le 06/03/2003 08:11:41

Pas tout à fait.

Commentaire de mahhoura le 23/01/2004 16:08:04

Bonjour Monsieur il y a une Classe TCPListner qui fait tout ce boulot reste a organiser le travail de sockets en les insérant dans un arrayList par exemple et de cette façon ton prog pourra gérer un nombre assez géant de connexions

Commentaire de demidali le 09/02/2005 22:49:28

Bonjour !

J'utilise les mêmes outils que vous pour avoir un service Windows qui écoute sur un port XXX.  Ce service écoute sur un serveur Windows 2000.  J'ai une application qui parle à ce service.  La ligne de code networkstream.read(byte,0,...) retourne seulement le premier caractère de la chaine envoyé au service.  Si je met le service sur un PC Windows XP, la string est complète sans changer aucune ligne de code ...

Pouvez-vous m'aider ou me référer.  Je cherche depuis 2 semaines, je suis pas mal désespéré ...

Merci !

Commentaire de lassad_haddaji le 14/12/2008 13:37:04

manque de commentaire

 Ajouter un commentaire


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


Nos sponsors


Sondage...

Comparez les prix

CalendriCode

Février 2012
LMMJVSD
  12345
6789101112
13141516171819
20212223242526
272829    

Consulter la suite du CalendriCode

Photothèque

 
Développement réalisé par Nicolas SOREL (Nix) avec l'aide de : Cyril DURAND et Emmanuel (EBArtSoft), Merci à Vincent pour ses précieux conseils.
CodeS-SourceS.com© Toute reproduction même partielle est interdite sauf accord écrit du Webmaster
CodeS-SourceS.com© est une marque déposée tous droits réservés

Google Coop CodeS-SourceS Google Coop CodeS-SourceS
Temps d'éxécution de la page : 1,310 sec (4)

Nous contacter | Annoncer sur CodeS-SourceS | Mentions légales