0

I have example code based on windows form application in .NET but I want to implement same code in web application.I can use same methods and classes in web app but there is one method (backgroundworker) which is not working in web application.I tried using background worker in aspx but I am not able to establish connection.

This is my windows form application code

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)
    {

    }
    }
  }

Is it possible to use this code to built web application or can you give me any sample code which use TCP/IP protocol in client server communication in web app.Please help.Thanks in advance

R.zeiwald
  • 236
  • 1
  • 5
  • 19

1 Answers1

1

Have a look at this question for a narrow answer to "how can I use a TCP client".

Your code is trying to use an asynchronous background worker, which doesn't make sense in the context of a web page request - the page request code ends when the method completes.

It's generally a really, really bad idea to make synchronous calls to external systems in the context of a page request unless you can be certain that external system is at least as fast and scalable as your web app - if it's slow, you will tie up lots of web workers waiting for that service, which will very quickly bring your web server down.

Instead, consider an asynchronous solution - see this project, for instance.

Community
  • 1
  • 1
Neville Kuyt
  • 29,247
  • 1
  • 37
  • 52