Accueil > Forum > > > > Probleme de multithread (coté serveur) sur un socket en c#
Probleme de multithread (coté serveur) sur un socket en c#
vendredi 11 février 2005 à 16:25:11 |
Probleme de multithread (coté serveur) sur un socket en c#

rossjulian
|
Bonjour, je suis tjs sur mon serveur de socket en c# et je n'arrive pas a traiter le multithread coté serveur.
je t'envoi mon code pour m'aider un peu
Merci d'avance Julien
CODE C# : Désolé pour la libilisité (C un projet Application Console en VS.net)
using System; using System.IO; using System.Threading; // Sleeping using System.Net; // Used to local machine info using System.Net.Sockets; // Socket namespace using System.Collections; // Access to the Array list using System.Data.SqlClient; using System.Data.Odbc;
namespace Socketsrv { /// <summary> /// Main class from which all objects are created /// </summary> class AppMain { // Attributes private ArrayList m_aryClients = new ArrayList(); // List of Client Connections public static int iniveautrace; public static string strpathtrace; public static string strpathappli;
private Thread tc;
//--------------------------------------------- // Procédure : // Permet la Trace du programme dans un fichier //---------------------------------------------
public static void FicTrace ( int MonNiveauTrace, string MonChemin, string MaChaine ) { DateTime now = DateTime.Now; if (MonNiveauTrace <= iniveautrace) { if (!File.Exists(MonChemin)) { TextWriter fileInfo = new StreamWriter(MonChemin); fileInfo.WriteLine(/*now.DayOfWeek.ToString("G") + " " +*/now.ToString("G") + ":" + now.Millisecond + " ----> " + MaChaine ); fileInfo.Close(); } else { StreamWriter fileInfo = File.AppendText(MonChemin); fileInfo.WriteLine(/*now.DayOfWeek.ToString("G")+ " " +*/now.ToString("G") + ":" + now.Millisecond + " ----> " + MaChaine); fileInfo.Close(); } } }
/// <summary> /// Point d'entrée principal de l'application. /// </summary> [STAThread] static void Main(string[] args) { // Repertoire par défaut de l'application strpathappli = Directory.GetCurrentDirectory() ;
// Emplacement du fichier de trace strpathtrace = TXCom.File.Ini.INILit("TRACE","PATH",strpathappli + "\\trace.txt",strpathappli);
// Port de communication dans un fichier ini string strport; strport = TXCom.File.Ini.INILit("PARAMETRE","PORT","399",strpathappli);
// Niveau de la trace iniveautrace = Convert.ToInt32(TXCom.File.Ini.INILit("TRACE","NIVEAU","0",strpathappli));
// Taille Maximum string strtaillemax; int itaillemax; strtaillemax= TXCom.File.Ini.INILit("TRACE","TAILLE MAX","10000",strpathappli); itaillemax = Convert.ToInt32(strtaillemax);
AppMain app = new AppMain();
// Determine the IPAddress of this machine IPAddress [] aryLocalAddr = null; string strHostName = ""; try { // NOTE: DNS lookups are nice and all but quite time consuming. strHostName = Dns.GetHostName(); IPHostEntry ipEntry = Dns.GetHostByName( strHostName ); aryLocalAddr = ipEntry.AddressList; } catch( Exception ex ) { FicTrace(0,strpathtrace,"Error trying to get local address " + ex.Message); Console.WriteLine ("Error trying to get local address {0} ", ex.Message ); }
// Verify we got an IP address. Tell the user if we did if( aryLocalAddr == null || aryLocalAddr.Length < 1 ) { FicTrace(0,strpathtrace,"Unable to get local address"); Console.WriteLine( "Unable to get local address" ); return; }
FicTrace(1,strpathtrace,"Listening on :" + strHostName + ":" + aryLocalAddr[0] + ":" + Convert.ToInt32(strport) ); Console.WriteLine( "Listening on : [{0}] {1}:{2}", strHostName, aryLocalAddr[0], Convert.ToInt32(strport) );
// Create the listener socket in this machines IP address Socket listener = new Socket( AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp ); listener.Bind( new IPEndPoint( aryLocalAddr[0], Convert.ToInt32(strport))); listener.Listen( 10 );
/*//Démarrage du thread avant la première connexion client
Thread getReadClients = new Thread(new ThreadStart(getRead));
getReadClients.Start();
//Démarrage du thread vérifiant l'état des connexions clientes
Thread pingPongThread = new Thread(new ThreadStart(CheckIfStillConnected));
pingPongThread.Start();
//Boucle infinie
while(true) {
Console.WriteLine("Attente d'une nouvelle connexion...");
//L'exécution du thread courant est bloquée jusqu'à ce qu'un
//nouveau client se connecte
listener.BeginAccept( new AsyncCallback( app.OnConnectRequest ), listener );
}*/
listener.BeginAccept( new AsyncCallback( app.OnConnectRequest ), listener );
FicTrace(2,strpathtrace,"Taper Enter pour quitter"); Console.WriteLine ("Taper Enter pour quitter"); Console.ReadLine(); Console.WriteLine ("OK! Tu es déconnecté" );
// Clean up before we go home listener.Close(); FicTrace(1,strpathtrace,"Fermeture du listener"); GC.Collect(); GC.WaitForPendingFinalizers(); }
/// <summary> /// Callback used when a client requests a connection. /// Accpet the connection, adding it to our list and setup to /// accept more connections. /// </summary> /// <param name="ar"></param> public void OnConnectRequest( IAsyncResult ar ) { Socket listener = (Socket)ar.AsyncState; NewConnection( listener.EndAccept( ar ) ); FicTrace(2,strpathtrace,"Nouvelle connexion"); listener.BeginAccept( new AsyncCallback( OnConnectRequest ), listener ); }
/// <summary> /// Add the given connection to our list of clients /// Note we have a new friend /// Send a welcome to the new client /// Setup a callback to recieve data /// </summary> /// <param name="sockClient">Connection to keep</param> public void NewConnection( Socket sockClient ) { // Program blocks on Accept() until a client connects. //SocketClient client = new SocketClient( listener.AcceptSocket() ); SocketClient client = new SocketClient( sockClient ); m_aryClients.Add( client );
FicTrace(1,strpathtrace,"Le Client " + IPAddress.Parse(((IPEndPoint)client.Sock.RemoteEndPoint).Address.ToString()) + " se connecte avec le port : " + ((IPEndPoint)client.Sock.RemoteEndPoint).Port.ToString()); Console.WriteLine( "Le Client " + IPAddress.Parse(((IPEndPoint)client.Sock.RemoteEndPoint).Address.ToString()) + " se connecte avec le port : " + ((IPEndPoint)client.Sock.RemoteEndPoint).Port.ToString());
// DateTime strDateLine = DateTime.Now; // // Convert to byte array and send. // Byte[] byteDateLine = System.Text.Encoding.ASCII.GetBytes( strDateLine.ToString()); // client.Sock.Send( byteDateLine, byteDateLine.Length, 0 ); client.SetupRecieveCallback( this );
} //---------------------------------------------------------- // Fonction : Retourne une chaine de caractères // Extraction d'un paramètre de la chaine envoyée au serveur //----------------------------------------------------------
public string ExtraireChaine ( string MaChaine, char separ, int iNumParam ) { string Result=""; int iPosIni = 0; int iPosFin = 0; int iNumOcc = 0;
for(int ii = 0 ; ii < MaChaine.Length ; ii++) { if(MaChaine[ii].CompareTo(separ)==0) { iNumOcc++; ii++; if(iNumOcc == iNumParam-1) { iPosIni = ii; } if(iNumOcc == iNumParam) { iPosFin = ii; Result = MaChaine.Substring(iPosIni,iPosFin-iPosIni-1); return Result; } } } if(iPosFin == 0) { if (iPosIni != 0) { Result = MaChaine.Substring(iPosIni,MaChaine.Length-iPosIni); } else { Result = ""; } } return Result; }
/// <summary> /// Get the new data and send it out to all other connections. /// Note: If not data was recieved the connection has probably /// died. /// </summary> /// <param name="ar"></param> public void OnRecievedData( IAsyncResult ar ) { // Déclaration de chaînes string strchaine, strliberror; int irow = 0; string strreponse = ""; // Séparateur de chaine char separch1 = (char)Convert.ToInt32(TXCom.File.Ini.INILit("PARAMETRE","SEPARDEBUTLIGNE","01",strpathappli)); char separch2 = (char)Convert.ToInt32(TXCom.File.Ini.INILit("PARAMETRE","SEPARPARAM","02",strpathappli)); char separch3 = (char)Convert.ToInt32(TXCom.File.Ini.INILit("PARAMETRE","SEPARSOUSPARAM","03",strpathappli)); char separch4 = (char)Convert.ToInt32(TXCom.File.Ini.INILit("PARAMETRE","SEPARFINLIGNE","04",strpathappli)); char separligne = (char)Convert.ToInt32(TXCom.File.Ini.INILit("PARAMETRE","SEPARLIGNE","03",strpathappli)); char separcolonne = (char)Convert.ToInt32(TXCom.File.Ini.INILit("PARAMETRE","SEPARCOLONNE","124",strpathappli));
// Elément pour constituer le message string strnom; string strtype = "";
SocketClient client = (SocketClient)ar.AsyncState; byte [] aryRet = client.GetRecievedData( ar ); strchaine = System.Text.Encoding.ASCII.GetString(aryRet);
//On envoie la chaine dans une procedure qui va décortiquer les differents parametres
strnom = ExtraireChaine (strchaine,separch2,1); strtype = ExtraireChaine (strchaine,separch2,2);
// Selon le type utilisé switch (strtype.ToUpper()) { case "" : return; //break;
case "SQL" : // Le cas où le type = SQL string strconnect; string strrequete;
// Eléments pour la connection (strconnect) string strtypeconnect; string strbaseconnect; string struserconnect; string strpassconnect; string strchaineconnect; string strrow = ""; string strerror = "";
//je décompose ma chaine en fonction du nombre de parametre attendus strconnect = ExtraireChaine (strchaine,separch2,3); strrequete = ExtraireChaine (strchaine,separch2,4); strrequete = ExtraireChaine (strrequete,separch4,1);
//strConnect est une chaine composée du type, de la base, du user, du password et chaine de connexion serveur
strtypeconnect = ExtraireChaine (strconnect,separch3,1); strbaseconnect = ExtraireChaine (strconnect,separch3,2);
switch (strtypeconnect) { case "SQLSERVER" :
//strConnect est une chaine composée du type, de la base, du user, du password et chaine de connexion serveur struserconnect = ExtraireChaine (strconnect,separch3,3); strpassconnect = ExtraireChaine (strconnect,separch3,4); strchaineconnect = ExtraireChaine (strconnect,separch3,5);
// Chaîne de connexion string connectString = "database="+strbaseconnect+";server="+strchaineconnect+";User ID="+struserconnect+";pwd="+strpassconnect; //Console.WriteLine(connectString);
try { // Objet connection SqlConnection connection = new SqlConnection(connectString);
// Ouverture de la connection connection.Open();
// Objet Command SqlCommand command = new SqlCommand(strrequete, connection);
// Selon le type de requête utilisée switch (strrequete.Substring(0,6).ToUpper()) { // Si la requete est un select case "SELECT" : // Objet DataReader SqlDataReader reader = command.ExecuteReader(); Object[] row = null; while (reader.Read()) { if (row == null) { row = new Object[reader.FieldCount]; } reader.GetValues(row); for (int i=0; i<row.GetLength(0); i++) { if (row[i] != DBNull.Value) { Console.Write(row[i]); strrow = strrow + row[i]; } else { Console.Write("NULL"); strrow = strrow + "NULL"; } if (i<row.GetUpperBound(0)) { Console.Write(separcolonne); strrow = strrow + separcolonne.ToString(); } } Console.WriteLine(); strrow = strrow + separch3; irow ++; } // Fermeture reader reader.Close(); strerror = "NO_ERROR"; strreponse = strnom + separch2 + strerror + separch2 + irow + separch2 + strrow + separch4; Console.WriteLine(strreponse); break;
// Si la requete est un non select case "INSERT" : case "UPDATE" : case "DELETE" : // Execution Console.WriteLine(strrequete); int affectedrows = command.ExecuteNonQuery(); Console.WriteLine("Nombre de lignes affectées {0}", affectedrows); strerror = "NO_ERROR"; strreponse = strnom + separch2 + strerror + separch2 + affectedrows + separch4; break;
default : strreponse = "La requête n'est pas valide"; break; } // Fermeture connection.Close(); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.Message); strerror = "ERROR"; strliberror = ex.Message; strreponse = strnom + separch2 + strerror + separch2 + strliberror + separch4; } Console.WriteLine(strreponse); aryRet = System.Text.Encoding.ASCII.GetBytes(strreponse); break;
case "ODBC" : try { // Objet connection OdbcConnection connection = new OdbcConnection (); connection.ConnectionString = "FIL=" + strtypeconnect + ";DSN=" + strbaseconnect;
// Ouverture de la connection connection.Open();
// Objet Command OdbcCommand myCommand = new OdbcCommand(strrequete,connection);
// Selon le type de requête utilisée switch (strrequete.Substring(0,6).ToUpper()) { // Si la requete est un select case "SELECT" : // Objet DataReader OdbcDataReader reader = myCommand.ExecuteReader();
Object[] row = null; while (reader.Read()) { if (row == null) { row = new Object[reader.FieldCount]; } reader.GetValues(row); for (int i=0; i<row.GetLength(0); i++) { if (row[i] != DBNull.Value) { Console.Write(row[i]); strrow = strrow + row[i]; } else { Console.Write("NULL"); strrow = strrow + "NULL"; } if (i<row.GetUpperBound(0)) { Console.Write(separcolonne); strrow = strrow + separcolonne.ToString(); } } Console.WriteLine(); strrow = strrow + separch3; irow ++; } // Fermeture reader reader.Close(); strerror = "NO_ERROR"; strreponse = strnom + separch2 + strerror + separch2 + irow + separch2 + strrow + separch4; Console.WriteLine(strreponse); break;
// Si la requete est un non select case "INSERT" : case "UPDATE" : case "DELETE" : // Execution int affectedrows = myCommand.ExecuteNonQuery(); Console.WriteLine("Nombre de lignes affectées {0}", affectedrows); strerror = "NO_ERROR"; strreponse = strnom + separch2 + strerror + separch2 + affectedrows + separch4; break;
default : strreponse = "La requête n'est pas valide"; break; } // Fermeture connection.Close(); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.Message); strerror = "ERROR"; strliberror = ex.Message; strreponse = strnom + separch2 + strerror + separch2 + strliberror + separch4; } Console.WriteLine(strreponse); aryRet = System.Text.Encoding.ASCII.GetBytes(strreponse); break;
case "HF" : try {
} catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.Message); strerror = "ERROR"; strliberror = ex.Message; strreponse = strnom + separch2 + strerror + separch2 + strliberror + separch4; } Console.WriteLine(strreponse); aryRet = System.Text.Encoding.ASCII.GetBytes(strreponse); break; } break;
////////////////////////////////////////////////////////////////////////////////////////////
// Le cas où le Type == FILE case "FILE" : // Eléments pour le fichier string strtypefic; string strchemin; string strtextfic = "";
strtypefic = ExtraireChaine (strchaine,separch2,3); try { strchemin = ExtraireChaine (strchaine,separch2,4); switch (strtypefic) { case "FILELINEREAD" : //2 ou 3 parametres int inbligne = 0; string strNumLigneIni = ""; string strNumLigneFin = "";
if (!File.Exists(strchemin)) { strerror = "ERROR"; FicTrace(0,strpathtrace,"Le fichier " + strchemin + " n'a pas été trouvé"); strtextfic = "Le fichier " + strchemin + " n'a pas été trouvé"; } else { int cpt = 0; int ii = 0; string strcha; strerror = "NO ERROR"; StreamReader reader = File.OpenText(strchemin);
// j'ai 2 ou 3 parametres strNumLigneIni = ExtraireChaine (strchaine, separch2,5); strNumLigneFin = ExtraireChaine(ExtraireChaine (strchaine, separch2,6),separch4,1);
if (strNumLigneFin == "") { // on a juste un numero de ligne à lire while( (strcha = reader.ReadLine()) != null) { cpt ++; if ( cpt == Convert.ToInt32(strNumLigneIni)) { strtextfic = strtextfic + strcha; inbligne = 1; }
} } else { // on a un numéro de début et de fin while( (strcha = reader.ReadLine()) != null) { ii ++; if ((ii >= Convert.ToInt32(strNumLigneIni)) && (ii <= Convert.ToInt32(strNumLigneFin))) { strtextfic = strtextfic + strcha; strtextfic = strtextfic + separligne; inbligne ++; } } } Console.WriteLine(strtextfic); } strreponse = strnom + separch2 + strerror + separch2 + inbligne + separch2 + strtextfic + separch4; break;
case "FILEREAD" : if (!File.Exists(strchemin)) { strerror = "ERROR"; FicTrace(0,strpathtrace,"Le fichier " + strchemin + " n'a pas été trouvé"); strtextfic = "Le fichier " + strchemin + " n'a pas ete trouve"; } else { strerror = "NO ERROR"; string strNumIni = ""; string strNumFin = "";
strNumIni = ExtraireChaine (strchaine, separch2,5); strNumFin = ExtraireChaine(ExtraireChaine (strchaine, separch2,6),separch4,1); if (strNumFin == "") { strNumFin = strNumIni; strNumIni = "0"; } string strcha; string strmachaine = "";
using (StreamReader reader = new StreamReader(strchemin)) { while ((strcha = reader.ReadLine()) != null) { strmachaine = strmachaine + strcha; } for (int ii = 0; ii <= Convert.ToInt32(strNumFin); ii++) { if (ii >= Convert.ToInt32(strNumIni)) { strtextfic = strtextfic + strmachaine[ii]; } } } } strreponse = strnom + separch2 + strerror + separch2 + strtextfic + separch4; break;
case "FILECOPY" : string strchemindestinataire = ExtraireChaine(ExtraireChaine(strchaine, separch2,5),separch4,1); if (!File.Exists(strchemin)) { strerror = "ERROR"; FicTrace(0,strpathtrace,"Le fichier " + strchemin + " n'a pas ete trouve"); strtextfic = "Le fichier " + strchemin + " n'a pas ete trouve"; } else { if (File.Exists(strchemindestinataire)) { File.Delete(strchemindestinataire); } strerror = "NO_ERROR"; File.Copy(strchemin,strchemindestinataire); strtextfic = "Le fichier " + strchemin + " a ete copie a l'emplacement " + strchemindestinataire + "."; } strreponse = strnom + separch2 + strerror + separch2 + strtextfic + separch4; break;
case "FILEMOVE" : string strchemindest = ExtraireChaine(ExtraireChaine(strchaine, separch2,5),separch4,1); if (!File.Exists(strchemin)) { strerror = "ERROR"; FicTrace(0,strpathtrace,"Le fichier " + strchemin + " n'a pas ete trouve"); strtextfic = "Le fichier " + strchemin + " n'a pas ete trouve"; } else { if (File.Exists(strchemindest)) { File.Delete(strchemindest); } strerror = "NO_ERROR"; File.Copy(strchemin,strchemindest); File.Delete(strchemin); strtextfic = "Le fichier " + strchemin + " a ete deplace a l'emplacement " + strchemindest + "."; } strreponse = strnom + separch2 + strerror + separch2 + strtextfic + separch4; break;
case "FILEINFO" : string strOption = ""; if (!File.Exists(strchemin)) { strerror = "ERROR"; FicTrace(0,strpathtrace,"Le fichier " + strchemin + " n'a pas ete trouve"); strtextfic = "Le fichier " + strchemin + " n'a pas ete trouve"; } else { strOption = ExtraireChaine(ExtraireChaine(strchaine, separch2,5),separch4,1); strerror = "NO_ERROR";
switch (strOption) { case "0" : string strcha; string strmachaine = ""; int iLongFic; using (StreamReader reader = new StreamReader(strchemin)) { while ((strcha = reader.ReadLine()) != null) { strmachaine = strmachaine + strcha; } } iLongFic = strmachaine.Length; strOption = "0 - longueur du fichier : " + iLongFic; break; case "1" : DateTime iCreateDateHeure; iCreateDateHeure = File.GetCreationTime(strchemin); strOption = "1 - date et heure de creation : " + iCreateDateHeure; break; case "2" : DateTime iModifDateHeure; iModifDateHeure = File.GetLastWriteTime(strchemin); strOption = "2 - date et heure de derniere modification : " + iModifDateHeure; break; case "3" : DateTime iDernierDateHeure; iDernierDateHeure = File.GetLastAccessTime(strchemin); strOption = "3 - date et heure de dernier acces : " + iDernierDateHeure; break; default : strerror ="ERROR"; strOption = "Numero incorrect"; break; } } strreponse = strnom + separch2 + strerror + separch2 + strOption + separch4; break;
case "FILELINEWRITE" : string strmaligne = ExtraireChaine(ExtraireChaine(strchaine, separch2,5),separch4,1); if (!File.Exists(strchemin)) { strerror = "ERROR"; FicTrace(0,strpathtrace,"Le fichier " + strchemin + " n'a pas ete trouve"); strtextfic = "Le fichier " + strchemin + " n'a pas ete trouve"; } else { strerror = "NO ERROR"; StreamWriter fileInfo = File.AppendText(strchemin); fileInfo.WriteLine("" + (char)10 + (char)13 + strmaligne); fileInfo.Close(); FicTrace(1,strpathtrace,"La ligne " + strmaligne + " a ete ajoute au fichier " + strchemin ); strtextfic = "La ligne " + strmaligne + " a ete ajoute"; } strreponse = strnom + separch2 + strerror + separch2 + strtextfic + separch4; break;
case "FILEWRITE" : string strnewchaine = ExtraireChaine(ExtraireChaine(strchaine, separch2,5),separch4,1); if (!File.Exists(strchemin)) { strerror = "ERROR"; FicTrace(0,strpathtrace,"Le fichier " + strchemin + " n'a pas ete trouve"); strnewchaine = ""; } else { strerror = "NO ERROR"; StreamWriter fileInfo = File.AppendText(strchemin); fileInfo.Write(strnewchaine + " "); fileInfo.Close(); FicTrace(1,strpathtrace,"La chaine " + strnewchaine + " a ete ajoute au fichier " + strchemin ); } strreponse = strnom + separch2 + strerror + separch2 + strnewchaine + separch4; break;
case "FILEGETLENGTH" : strchemin = ExtraireChaine(strchemin,separch4,1); if (!File.Exists(strchemin)) { strerror = "ERROR"; FicTrace(0,strpathtrace,"Le fichier " + strchemin + " n'a pas ete trouve"); strtextfic = "Le fichier " + strchemin + " n'a pas ete trouve"; strreponse = strnom + separch2 + strerror + separch2 + strtextfic + separch4; } else { strerror = "NO_ERROR"; string strtext; string strchainelue = ""; int ilongueurfic; using (StreamReader reader = new StreamReader(strchemin)) { while ((strtext = reader.ReadLine()) != null) { strchainelue = strchainelue + strtext; } } ilongueurfic = strchainelue.Length; strreponse = strnom + separch2 + strerror + separch2 + ilongueurfic + separch4; } break;
case "FILESETLENGTH" : int ilongfic; if (!File.Exists(strchemin)) { strerror = "ERROR"; FicTrace(0,strpathtrace,"Le fichier " + strchemin + " n'a pas ete trouve"); strtextfic = "Le fichier " + strchemin + " n'a pas ete trouve"; ilongfic = 0; } else { string strmachaine = ""; string strcha; string strlongfic = ExtraireChaine(ExtraireChaine(strchaine, separch2,5),separch4,1); strerror = "NO ERROR"; using (StreamReader reader = new StreamReader(strchemin)) { while ((strcha = reader.ReadLine()) != null) { strmachaine = strmachaine + strcha; } } if ((Convert.ToInt32(strlongfic)) <= strmachaine.Length) { using (StreamWriter writer = new StreamWriter(strchemin)) { for ( int ii = 0 ; ii < (Convert.ToInt32(strlongfic)) ; ii++) { writer.Write(strmachaine[ii]); } } } else { using (StreamWriter writer = new StreamWriter(strchemin)) { for ( int ii = 0 ; ii < (Convert.ToInt32(strlongfic)) ; ii++) { if ( ii >= strmachaine.Length) { writer.Write(" "); } else { writer.Write(strmachaine[ii]); } } } } ilongfic = Convert.ToInt32(strlongfic); } strreponse = strnom + separch2 + strerror + separch2 + ilongfic + separch4; break;
case "FILEDELETE" : string strnewchemin = ExtraireChaine(strchemin,separch4,1); if (!File.Exists(strnewchemin)) { strerror = "ERROR"; FicTrace(0,strpathtrace,"Le fichier " + strnewchemin + " n'a pas été trouve"); strtextfic = "Le fichier " + strchemin + " n'a pas ete trouve"; } else { strerror = "NO_ERROR"; File.Delete(strnewchemin); strtextfic = "Le fichier " + strnewchemin + " a ete efface"; } strreponse = strnom + separch2 + strerror + separch2 + strtextfic + separch4; break;
default : strerror = "ERROR"; strtextfic = "Le type de fichier " + strtypefic + " n'est pas valide"; strreponse = strnom + separch2 + strerror + separch2 + strtextfic + separch4; FicTrace(1,strpathtrace,"Le type de fichier " + strtypefic + " n'est pas valide"); break; } } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.Message); strerror = "ERROR"; strliberror = ex.Message; strreponse = strnom + separch2 + strerror + separch2 + strliberror + separch4; } aryRet = System.Text.Encoding.ASCII.GetBytes(strreponse); break;
// Les autres cas default : strreponse = "Invalid type : " + strtype.ToUpper().ToString() + " : " + strchaine.ToString(); aryRet = System.Text.Encoding.ASCII.GetBytes(strreponse); break; }
// If no data was recieved then the connection is probably dead if( aryRet.Length < 1 ) { FicTrace(0,strpathtrace,"Le Client " + IPAddress.Parse(((IPEndPoint)client.Sock.RemoteEndPoint).Address.ToString()) + " s'est déconnecté avec le port : " + ((IPEndPoint)client.Sock.RemoteEndPoint).Port.ToString()); Console.WriteLine( "Le Client " + IPAddress.Parse(((IPEndPoint)client.Sock.RemoteEndPoint).Address.ToString()) + " s'est déconnecté avec le port : " + ((IPEndPoint)client.Sock.RemoteEndPoint).Port.ToString()); return; }
// Envoyer le message à tous les clients connectés foreach( SocketClient clientSend in m_aryClients ) { try { if ( clientSend.Sock.RemoteEndPoint == client.Sock.RemoteEndPoint) { clientSend.Sock.SendTo( aryRet, client.Sock.RemoteEndPoint); FicTrace(2,strpathtrace,"Envoi au client : " + client.Sock.RemoteEndPoint + " du message : " + strreponse); } } catch { // If the send fails the close the connection FicTrace(0,strpathtrace,"Send to client " + client.Sock.RemoteEndPoint + " failed "); Console.WriteLine( "Send to client {0} failed", client.Sock.RemoteEndPoint ); client.Sock.Close(); m_aryClients.Remove( client ); return; } } client.SetupRecieveCallback( this ); } }
/// <summary> /// Class holding information and buffers for the Client socket connection /// </summary> internal class SocketClient { private Socket m_sock; // Connection to the client private byte[] m_byBuff = new byte[5000]; // Receive data buffer /// <summary> /// Constructor /// </summary> /// <param name="sock">client socket connection this object represents</param> public SocketClient( Socket sock ) { m_sock = sock; }
// Readonly access public Socket Sock { get{ return m_sock; } }
/// <summary> /// Setup the callback for recieved data and loss of connection /// </summary> /// <param name="app"></param> public void SetupRecieveCallback( AppMain app ) { try { AsyncCallback recieveData = new AsyncCallback(app.OnRecievedData); m_sock.BeginReceive(m_byBuff, 0, m_byBuff.Length, SocketFlags.None, recieveData, this ); } catch( Exception ex ) { Socketsrv.AppMain.FicTrace(0,AppMain.strpathtrace,"Recieve callback setup failed! " + ex.Message ); Console.WriteLine( "Recieve callback setup failed! {0}", ex.Message ); } }
/// <summary> /// Data has been recieved so we shall put it in an array and /// return it. /// </summary> /// <param name="ar"></param> /// <returns>Array of bytes containing the received data</returns> public byte [] GetRecievedData( IAsyncResult ar ) { int nBytesRec = 0; try { nBytesRec = m_sock.EndReceive( ar ); } catch{} byte [] byReturn = new byte[nBytesRec];
Array.Copy( m_byBuff, byReturn, nBytesRec );
/* // Check for any remaining data and display it // This will improve performance for large packets // but adds nothing to readability and is not essential int nToBeRead = m_sock.Available; if( nToBeRead > 0 ) { byte [] byData = new byte[nToBeRead]; m_sock.Receive( byData ); // Append byData to byReturn here } */ return byReturn;
} } }
|
|
vendredi 11 février 2005 à 20:28:00 |
Re : Probleme de multithread (coté serveur) sur un socket en c#
|
Cette discussion est classée dans : string, client, strchemin, separch2, strerror
Répondre à ce message
Sujets en rapport avec ce message
echange de données par le net [ par gomoz ]
je n'en peux plus...Je ne comprends pas d'où viens le problème. Je fais un programme client/serveur, j'ai programmé une grande partie du serveur et un
Problème de data reader [ par lefreeman42 ]
Bonjour tout le monde ^^J'aimerais faire une mise à jour d'une table MySQL à partir d'un fichier XML : <Client Numero="1" Nom="Dupond" Prenom="Jean"
Socket - send - data [ par Nairda ]
Bonjour, Je suis relativement nouveau dans le monde du .net et plus particulière en C#. J'ai un petit problème de conception et j'espère que vous pour
Ajouter une requête à mon formulaire [ par angedb9 ]
je suis débutant et je ne comprends pas pourquoi ma requête ne s'execute pas. Après la saisie dans les différents textbox,mask et richbox on fait un c
Struct??Comment faire? [ par Fildomen ]
Salutj'ai tapé ce bout de code:public struct CBoot{public string Message_provenant_du_serveur = "00000";public string fmConnexion_Demande_de_connexion
Enlever les accents d'un string [ par SharpMao ]
Hello,Je cherche un moyen d'enlever les accents d'un string, si possible sans passer par du ASCIIEncoding, qui met d'autres charactères à la place.En
Insertion de données dans une base [ par Kleidp ]
Bonjour, voici mon problème:J'essai d'insérer des données dans 2 tables liées par une clef primaire et étrangère. Les données sont affichées dans des
Type global pour int[], string[], bool[] ..... [ par ricklekebekoi ]
Hello,Mon problème va comme suit:Dans mon programme, jutilise différentes array de différents types (des bool[], des int[], des string[] ...)Je me sui
sécurité tcp/client [ par Fildomen ]
salutje peux savoir s'il existe ou peut exister des applications qui peuvent avoir les données écrites dans les ports???mercihttp://www.devportail.tk
Etablir une connexion Tcp/Client [ par Fildomen ]
SalutPouvez-vous me donner un example d'une connexion tcp/client avec le c# 2005???c très compliqué que le c# 2003.merci
Livres en rapport
|
Derniers Blogs
UNE JOLIE-HORLOGE ET PAS QU'UN PEU !UNE JOLIE-HORLOGE ET PAS QU'UN PEU ! par neodante
Pour les possesseurs d'iPhone, ça y est Bijin Tokei - qui se traduit littéralement en Français par " Jolie Horloge " - est arrivé et GRATUITEMENT s'il vous plaît ! Après la version Tokyo, Hokkaido, night club, racing, Gal, "pour les mademoiselles'", . voi...
Cliquez pour lire la suite de l'article par neodante TECHDAYS PARIS 2010 : CONNECTEZ VOS DONNéES à SHAREPOINT 2010 AVEC LES BUSINESS CONNECTIVITY SERVICESTECHDAYS PARIS 2010 : CONNECTEZ VOS DONNéES à SHAREPOINT 2010 AVEC LES BUSINESS CONNECTIVITY SERVICES par ROMELARD Fabrice
Animé par: Gaetan Bouveret et Julien Chomarat Business Connectivity Services (BCS) est dans SharePoint 2010 la version 2 de Business Data Catalog (BDC dans SharePoint 2007). Il s'agit de la solution permettant de visualiser des données provenan...
Cliquez pour lire la suite de l'article par ROMELARD Fabrice [DIVERS] SUIVRE VOS SéRIES PRéFéRéS SUR LA TOILE[DIVERS] SUIVRE VOS SéRIES PRéFéRéS SUR LA TOILE par orion
Comme de nombreux geek, je suis un grand amateur de série TV et je rate régulièrement des épisodes de mes séries préférés. Une solution s'offre à vous avec ce merveilleux site : Tv Gorge - www.tvgorge.com Moteur de recherche à l'appui, vous pouvez ...
Cliquez pour lire la suite de l'article par orion TECHDAYS PARIS 2010 : LA BI DANS SHAREPOINT 2010TECHDAYS PARIS 2010 : LA BI DANS SHAREPOINT 2010 par ROMELARD Fabrice
Animé par: Vincent Bellet et Baptiste Giraudier La BI dans SharePoint 2010, Les nouveaux services d'application dans SP2010 et SQL Server Reporting services 2008 R2. La BI dans SharePoint est généralisée pour tous afin de permettre à tous les coll...
Cliquez pour lire la suite de l'article par ROMELARD Fabrice
Logiciels
DB-MAIN (9.1.0)DB-MAIN (9.1.0)DB-MAIN is a data-modeling and data-architecture tool. It is designed to help developers and anal... Cliquez pour télécharger DB-MAIN Xilisoft DPG Convertisseur (5.1.37.0120)XILISOFT DPG CONVERTISSEUR (5.1.37.0120)Xilisoft DPG Convertisseur offre aux fans de Nintendo DS une bonne solution leur permettant de dé... Cliquez pour télécharger Xilisoft DPG Convertisseur GraphicsGale (2.01.01)GRAPHICSGALE (2.01.01)GraphicsGale est un logiciel de PixelArt avec de nombreuse fonctionnalités permettant de réalisé ... Cliquez pour télécharger GraphicsGale Architecte 3D (Platinum 2010)ARCHITECTE 3D (PLATINUM 2010)Architecte 3D Platinium vous permet de concevoir facilement les plans votre future maison, de l'é... Cliquez pour télécharger Architecte 3D TeamViewer 5 (TeamViewer 5)TEAMVIEWER 5 (TEAMVIEWER 5)Dépanner un ami,expliquer une manipulation devient un jeu d'enfant.
Prise en main d'un autre ord... Cliquez pour télécharger TeamViewer 5
|