【问题标题】:TCP client in ASP.netASP.net 中的 TCP 客户端
【发布时间】:2012-06-08 14:54:55
【问题描述】:

我正在尝试从 asp web 应用程序连接到 tcp 服务器。我使用 C# 中的应用程序完成了这项工作,现在我想看看它是否可以在 Web 浏览器中运行。

我的代码是:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Net;
using System.Net.Sockets;

namespace TcpWebClient

{
    public partial class _Default : System.Web.UI.Page
{

    private byte[] data = new byte[1024];
    IPEndPoint ipep = new IPEndPoint(
            IPAddress.Parse("192.168.1.20"), 12000);

    Socket server = new Socket(AddressFamily.InterNetwork,
                   SocketType.Stream, ProtocolType.Tcp);


    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void Button1_Click(object sender, EventArgs e)
    {

        try
        {
            server.Connect(ipep);
        }
        catch (SocketException)
        {              
        }
    }

    protected void Button2_Click(object sender, EventArgs e)
    {
        NetworkStream ns = new NetworkStream(server);

        if (ns.CanWrite)
        {
            ns.Write(Encoding.ASCII.GetBytes("DI"), 0, 2);
            ns.Flush();
        }
        else
        {
        }
        TextBox1.Text = null;
        TextBox1.Text = Encoding.ASCII.GetString(data, 0, ns.Read(data, 0, data.Length));
    }

}
}

什么在工作?:我已连接到 tcp 服务器。但是当我想发送和接收一些数据时,我遇到了错误:

IOException was unhandled by user code and something like this: Operation is not supported on connected sockets (don't know if my translation to english is ok).

我做错了什么?

System.dll 中发生了“System.IO.IOException”类型的第一次机会异常

编辑:

这样的东西正在工作..但是我需要重新连接到服务器的每个计时器滴答声.. 是否可以建立一个连接,然后每个计时器滴答声读取/发送数据而不重新连接?

 protected void Timer1_Tick(object sender, EventArgs e)
    {

            server.Connect(ipep);
            NetworkStream stream = new NetworkStream(server);

            Byte[] data = System.Text.Encoding.ASCII.GetBytes("data");
            stream.Write(data, 0, data.Length);
            data = new Byte[256];
            Int32 bytes = stream.Read(data, 0, 8);
            responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
            TextBox1.Text = responseData;
            server.Close();

        }

【问题讨论】:

    标签: c# tcpclient .net


    【解决方案1】:

    您实际上回答了自己:连接未在您的第二个事件处理程序 (Button2_click) 中打开,因为您在 button1 单击时打开,它当然会与页面一起结束其生命周期,每个请求都会创建一个实例.

    您可以将打开的连接保存在静态变量中(如果您不介意连接被共享应用程序 - 对所有用户都适用),但我真的不确定您是否真的只使用您在编辑中发布的代码.
    如果您希望连接器在应用程序范围内可用,请将其变量定义为静态变量(但请确保在第一次尝试使用之前初始化/连接),您可以使用 .net 4 中提供的Lazy<T> 帮助器类来制作确保连接初始化一次,仅在第一次需要时。
    如果您还需要在其他类中访问连接,您可以创建一个单独的单例类来包装它(并在那里以相同的方式对其进行初始化)

    【讨论】:

      猜你喜欢
      • 2015-03-26
      • 1970-01-01
      • 1970-01-01
      • 2018-09-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多