2017-03-23 4 views
-1

J'ai un exemple de code basé sur l'application de formulaire Windows dans .NET mais je veux implémenter le même code dans une application web. Je peux utiliser les mêmes méthodes et classes dans l'application web mais il y a une méthode (backgroundworker) qui ne fonctionne pas dans l'application web. J'ai essayé d'utiliser background worker dans aspx mais je ne suis pas capable d'établir une connexion.Comment établir la communication du serveur client en utilisant le protocole TCP/IP dans l'application web .NET

C'est mes fenêtres forment le code d'application

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using System.Windows.Forms; 

using System.Net; 
using System.Net.Sockets; 
using System.IO; 

namespace ServerClient 
{ 
public partial class Form1 : Form 
{ 
    private TcpClient client; 
    public StreamReader STR; 
    public StreamWriter STW; 
    public String receive = "kkkk"; 
    public String text_to_send; 
    TcpListener listener; 
    public Form1() 
    { 
     InitializeComponent(); 
     IPAddress[] localIP = Dns.GetHostAddresses(Dns.GetHostName());    // get by own IP 
     foreach(IPAddress address in localIP) 
     { 
      if(address.AddressFamily == AddressFamily.InterNetwork) 
      { 
       textBox3.Text = address.ToString(); 
      } 
     } 
    } 

    private void Form1_Load(object sender, EventArgs e) 
    { 

    } 



    private void button2_Click(object sender, EventArgs e)    // start server 
    { 
     listener = new TcpListener(IPAddress.Any, int.Parse(textBox4.Text)); 
     listener.Start(); 
     client = listener.AcceptTcpClient(); 
     STR = new StreamReader(client.GetStream()); 
     STW = new StreamWriter(client.GetStream()); 
     STW.AutoFlush = true; 

     backgroundWorker1.RunWorkerAsync();  // start receiving data in background 
     backgroundWorker2.WorkerSupportsCancellation = true;  //Ability to cancel this thread 
    } 

    private void textBox5_TextChanged(object sender, EventArgs e) 
    { 

    } 

    private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) //receive data 
    { 
     NetworkStream stream = client.GetStream(); 
     Byte[] bytes = new Byte[256]; 
     String data = null; 
     int i; 

     // Loop to receive all the data sent by the client. 
     while ((i = stream.Read(bytes, 0, bytes.Length)) != 0) 
     { 
      // Translate data bytes to a ASCII string. 
      data = System.Text.Encoding.ASCII.GetString(bytes, 0, i); 
      byte[] bHex = Encoding.ASCII.GetBytes(data); 
      this.textBox2.Invoke(new MethodInvoker(delegate() { textBox2.AppendText("GSM:" + data + "\n"); })); 
      //Console.WriteLine("Received: {0}", data); 

      // Process the data sent by the client. 
      // data = data.ToUpper(); 

      //byte[] msg = System.Text.Encoding.ASCII.GetBytes(data); 

      // Send back a response. 
      // stream.Write(msg, 0, msg.Length); 
      //Console.WriteLine("Sent: {0}", data); 
     } 

    } 

    private void backgroundWorker2_DoWork(object sender, DoWorkEventArgs e)   //send data 
    { 
     if(client.Connected) 
     { 
      STW.WriteLine(text_to_send); 
      this.textBox2.Invoke(new MethodInvoker(delegate() { textBox2.AppendText("Me:" + text_to_send + "\n"); })); 
     } 
     else 
     { 
      MessageBox.Show("Send Failed!"); 
     } 
     backgroundWorker2.CancelAsync(); 
    } 
    private void button3_Click(object sender, EventArgs e) 
    { 
     client = new TcpClient(); 
     IPEndPoint IP_End = new IPEndPoint(IPAddress.Parse(textBox5.Text), int.Parse(textBox6.Text)); 

     try 

     { 
      client.Connect(IP_End); 
      if (client.Connected) 
      { 
       textBox2.AppendText("Connected To Server" + "\n"); 
       STW = new StreamWriter(client.GetStream()); 
       STR = new StreamReader(client.GetStream()); 
       STW.AutoFlush = true; 

       backgroundWorker1.RunWorkerAsync();  // start receiving data in background 
       backgroundWorker2.WorkerSupportsCancellation = true;   //Ability to cancel this thread 

      } 
     } 
     catch(Exception x) 
     { 
      MessageBox.Show(x.Message.ToString()); 
     }  

    } 

    private void button1_Click(object sender, EventArgs e)   // Send button 
    { 
     if(textBox1.Text != "") 
     { 
      text_to_send = textBox1.Text; 
      backgroundWorker2.RunWorkerAsync(); 

     } 
     textBox1.Text = ""; 
    } 

    private void textBox3_TextChanged(object sender, EventArgs e) 
    { 

    } 

    private void textBox4_TextChanged(object sender, EventArgs e) 
    { 

    } 
    } 
    } 

Est-il possible d'utiliser ce code à l'application Web intégré ou pouvez-vous me donner un exemple de code qui utilisent le protocole TCP/IP dans la communication client-serveur dans l'application web .S'il vous plaît aider.Merci à l'avance

Répondre

0

Jetez un oeil à this question pour une réponse étroite à "comment puis-je utiliser un client TCP".

Votre code essaie d'utiliser un agent de fond asynchrone, ce qui n'a pas de sens dans le contexte d'une demande de page Web - le code de demande de page se termine lorsque la méthode est terminée. C'est généralement une très, très mauvaise idée de faire des appels synchrones à des systèmes externes dans le contexte d'une demande de page, sauf si vous êtes certain que le système externe est au moins aussi rapide et évolutif que votre application web - si elle est lente, vous allez attacher beaucoup de web workers en attente de ce service, ce qui va très rapidement faire baisser votre serveur web. Au lieu de cela, considérons une solution asynchrone - voir par exemple project.