2016-04-01 1 views
0

Je fais quelque chose pour mon projet pour l'école, il me faut construire une application C# qui permet à la fois la communication du serveur (l'auditeur) et le client. Le problème est, j'ai fait ceci, mais cela ne fonctionne pas du tout, il jette trop d'erreurs pour corriger et est certainement mal codé, je n'ai jamais fait quelque chose de ce sloppy avant.Communication entre le serveur et la connexion client C#

Je voudrais également que de nombreux clients puissent accéder au serveur en même temps, donc une liste de clients actifs. J'ai vu un exemple en ligne mais c'était trop compliqué pour la tâche que j'essayais d'accomplir. Je veux juste une communication de texte simple au client et au serveur et envoyer l'information quand nécessaire. Je ne veux pas qu'il soit bloqué dans une boucle en attendant que l'information soit envoyée & Désolé, si je l'ai mal expliqué. Merci.

modifier

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 

using System.Windows.Forms; 
using System.Threading; 
using System.Net; 
using System.Net.Sockets; 

namespace CentralHubGUI 
{ 
    class chCon 
    { 



    static TcpClient clientCon; 
    static NetworkStream stream; 
    public static bool currentlyConnected; 

    static string buffer; 

    string ip = ""; 
    int port = 0; 

    Thread thread1 = new Thread(receiveData_Stage1); 
    //Thread thread2 = new Thread(); 
    //Thread thread3 = new Thread(); 

    public chCon(string ipAddress, int portNumber) 
    { 
     ip = ipAddress; 
     port = portNumber; 

     connectToConsole(); 
    } 

    public void connectToConsole()//mitigates the connection 
    { 
     if (ip.Trim() == "") 
      ip = "127.0.0.1"; 

     if (port == 0) 
      port = 2647; 

     try 
     { 
      clientCon = new TcpClient(ip, port); 
      stream = clientCon.GetStream(); 

      sendData("#101" + (char)13); //first bit of data is sent on accepted client 

      Thread retrieveData = new Thread(receiveData_Stage1); 
      retrieveData.Start(); 
      currentlyConnected = true; 

      thread1.Start(); //starting to read the server for information 
     } 

     catch(Exception e) // if the connection being naughty ;) 
     { 
      currentlyConnected = false; 
      MessageBox.Show("Exception caught:\n" + e); 
     } 

    } 

    public void disconnectFromConsole() 
    { 
     try 
     { 
      if (clientCon.Connected || clientCon.Connected == null) 
      { 
       thread1.Abort(); 

       byte[] msg = System.Text.Encoding.ASCII.GetBytes("#103"); 
       stream.Write(msg, 0, msg.Length); 
       stream.Close(); 
       clientCon.Close(); 

       currentlyConnected = false; 
      } 
      else 
      { 
       MessageBox.Show("Cannot disconnect from a connection that has not started."); 
      } 
     } 
     catch (Exception ex) 
     { 
      MessageBox.Show("Error thrown during disconnection - UNKNOWN"); 
     } 
    } 

    internal void sendData(string data)//sends data to the server 
    { 
     Byte[] dataConv = System.Text.Encoding.ASCII.GetBytes(data); 

     stream.Write(dataConv, 0, dataConv.Length); 

    } 

    public static void receiveData_Stage1() //builds a buffer through a loop 
    { 
     while (true) 
     { 
      Byte[] response = new Byte[256]; 
      string responseData = String.Empty; 

      // Read the first batch of the TcpServer response bytes. 
      Int32 bytes = stream.Read(response, 0, response.Length); 
      responseData = System.Text.Encoding.ASCII.GetString(response); 

      if(responseData.Trim() != "") 
       buffer = buffer + responseData; 
     } 
    } 

    public static string receiveData_Stage2() //requests the buffer through a return value string 
    { 
     string bufferTemp; 
     bufferTemp = buffer; 

     buffer = string.Empty; 

     return bufferTemp; 
    } 

    public void closeConnection() 
    { 
     stream.Close(); 
     clientCon.Close(); 
     thread1.Abort(); 
    } 

    } 
    /* 
    while (true) 
     { 
      if (Program.currentlyConnected == true) 
      { 
       Thread.Sleep(100); 
       buffer = Program.receiveData_Stage2(); 
       if (buffer != "") 
        richTxtBoxConsole.AppendText(buffer + "\n"); 
      } 
      else 
      { 
       guiConsoleWriteLine("Connection is not active."); 
       break; 
      } 

     } 
    */ 
} 
+0

Après ce que vous avez essayé. Sinon, c'est une question trop large. – Divisadero

+0

Cette question a besoin d'un travail sérieux. S'il vous plaît montrer exactement ce que vous avez essayé et quelles erreurs/problèmes que vous avez rencontrés que vous ne pouvez pas résoudre. – nodots

+0

** A) ** Pourquoi utilisez-vous deux threads pour lire les données? Cela pourrait causer des problèmes sérieux. Soit se débarrasser de «Thread1» ou «retrieveData». ** B) ** Vérifier 'clientCon.Connected == null' est inutile car une valeur' Boolean' ne peut pas être nulle. –

Répondre

0

D'après ce que vous nous avez expliqué que je ne peux pas vraiment comprendre ce que vous voulez, mais de mon deviner, disons que cela dépend de la technologie que vous voulez aller. Je recommande d'utiliser WCF Windows Communication Foundation. Vous pouvez trouver quelques bons articles sur .NET Foundation, Tutorial to get started