如何在.NET Web应用程序中使用TCP / IP协议建立客户端服务器通信

时间:2017-03-23 11:03:54

标签: c# asp.net web-applications tcp-ip aspx-user-control

我在.NET中有基于Windows窗体应用程序的示例代码但是我想在Web应用程序中实现相同的代码。我可以在Web应用程序中使用相同的方法和类但是有一种方法(backgroundworker)在web中不起作用application.I尝试在aspx中使用后台工作程序,但我无法建立连接。

这是我的Windows窗体应用程序代码

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

    }
    }
  }

是否可以使用此代码构建Web应用程序,或者您是否可以在Web应用程序中为客户端服务器通信中提供使用TCP / IP协议的任何示例代码。请帮助。提前感谢

1 个答案:

答案 0 :(得分:0)

请查看this问题以获得对#34的简短回答;如何使用TCP客户端"。

您的代码正在尝试使用异步后台工作程序,这在网页请求的上下文中没有意义 - 页面请求代码在方法完成时结束。

在页面请求的上下文中对外部系统进行同步调用通常是一个非常非常糟糕的主意,除非您可以确定外部系统至少与Web应用程序一样快速且可扩展 - 如果它很慢,你会占用很多等待该服务的网络工作者,这会很快导致你的网络服务器崩溃。

相反,请考虑异步解决方案 - 例如,请参阅此project