2015-11-26 74 views
0

試圖通過使用低級套接字在C#和java服務器中創建客戶端服務器客戶端應用程序: 過程如下 他們單擊登錄的計費客戶接口登錄或註冊 我打開我的套接字我發送請求到我的服務器,我啓動一個線程來不斷讀取服務器發送的數據:它運作良好: 除了我必須保持我的套接字爲隨後的調用,我知道如何做到這一點:SOS 這裏是一個代碼片段: /// T稱爲第一個呼叫服務器爲所有調用使用套接字的單個實例

public void Inscritpionidentification(string Commande,string UserID,string Password, string Nom,string prenom,string Email) 
     { 
      IPEndPoint ipEnd = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 2007); 
      ClientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); 
      try 
      { 
       ClientSocket.Connect(ipEnd); 
       if(ClientSocket.Connected) 
        { 
         //SendMsg(GetSequence()+NickName);     
         //Connect.Enabled=false; 
       if (Commande.Equals("/Identification")) 
      { 
      SendMsg("Identification");   

      } 
      if (Commande.Equals("/Account/Create")) 
      { 
       SendMsg("Inscription")); 
      } 

        } 



      } 
      catch (SocketException E) 
      { 
       MsgBox("Connection" + E.Message); 

      } 


      try 
      { 
       DataReceived = new Thread(new ThreadStart(CheckData)); // Read constantly gives the server sent 
       DataReceived.Start(); 
      } 
      catch (Exception E) 
      { 
       MsgBox("Démarrage Thread" + E.Message); 
         } 

      while (UTF8Content==null) { 

      } 
      // Traitement 


     } 

    void SendMsg(string message) 
    { 

     byte[] msg = System.Text.Encoding.UTF8.GetBytes(message); 
     int DtSent = ClientSocket.Send(msg, msg.Length, SocketFlags.None); 
     if (DtSent == 0) 
     { 
      MsgBox("aucune donnèe n'as ete envoyé"); 

     } 
    } 

//// My thread 
private void CheckData() 
     { 
      try 
      { 
       while(true) 
       { 

        if(ClientSocket.Connected) 
        { 
         if(ClientSocket.Poll(10,SelectMode.SelectRead) && ClientSocket.Available==0) 
         { 
          //La connexion a été clôturée par le serveur ou bien un problème 
          //réseau est apparu 
          MsgBox("La connexion au serveur est interrompue.Reessayez!!"); 

          Thread.CurrentThread.Abort(); 
         } 
        //Si la socket a des données à lire       
         if(ClientSocket.Available>0) 
         { 
           string messageReceived=null;                 
           while(ClientSocket.Available>0) 
           { 
             try 
             {     

              byte[] msg=new Byte[ClientSocket.Available]; 
              //Réception des données 
              ClientSocket.Receive(msg,0,ClientSocket.Available,SocketFlags.None); 
              messageReceived=System.Text.Encoding.UTF8.GetString(msg).Trim();            
              //On concatène les données reçues(max 4ko) dans une variable de la classe 
              UTF8Content+=messageReceived; 


             } 
             catch(SocketException E) 
             { 

             } 

           } 


         } 
        } 
        //On temporise pendant 10 millisecondes, ceci pour éviter 
        //que le micro processeur s'emballe 
        Thread.Sleep(10); 
       } 

      } 
      catch 
      {     
       //Ce thread étant susceptible d'être arrêté à tout moment 
       //on catch l'exception afin de ne pas afficher un message à l'utilisateur 
       Thread.ResetAbort(); 
      }     
     } 

//我在調用這個函數之後調用了這個函數,我必須使用在IdentificationInscription函數中實例化的相同的套接字,即使線程在執行時toujour DataRecevied也不是不可能的。任何幫助將不勝感激

public void ModifCompte(string UserID, string Password, string Nom, string prenom, string Email) { 

     SendMsg("Update"); // *Error Socket has null* 
     while (UTF8Content == null) 
     { 


     } 
     //My treatment 
    } 
+0

非常感謝你這是最後的解決方案 –

回答

1

看看單身模式https://msdn.microsoft.com/en-au/library/ff650316.aspx

實質上,你的單身人士會包裹你的套接字。您只能創建一個套接字實例並通過單例引用它。

如何管理何時打開和關閉套接字取決於您。

+0

你好,感謝您的回覆, 通過我的問題是我在下一次調用服務器時,我發現我的socket = null這是正常的,因爲每次調用我們所有的服務器變量都已初始化。 –

相關問題