简体   繁体   English

ASP.net中的TCP客户端

[英]TCP client in ASP.net

i'm trying to connect from asp web application to tcp server. 我正在尝试从ASP Web应用程序连接到TCP服务器。 I did this using application in C#, and now i'd like to see if it will be working from web browser. 我使用C#中的应用程序进行了此操作,现在我想看看它是否可以在Web浏览器中运行。

My code is: 我的代码是:

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));
    }

}
}

What is working?: I have connection to tcp server. 什么有效?:我已连接到TCP服务器。 But when i want to send and receive some data i'm getting errors: 但是,当我想发送和接收一些数据时,出现错误:

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

What i'm doing wrong? 我做错了什么?

A first chance exception of type 'System.IO.IOException' occurred in System.dll System.dll中发生类型为'System.IO.IOException'的第一次机会异常

EDIT: 编辑:

Something like this is working.. but every tick of timer i need to reconnect to the server.. is it possible to have one connection, then every tick of timer read/send data without reconnecting? 像这样的事情正在工作..但是我需要重新连接到服务器的每一个计时器滴答声..是否可以建立一个连接,然后每个计时器的滴答滴答滴答/发送数据而无需重新连接?

 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();

        }

You actually answered yourself: The connection is not openned in your second event handler (Button2_click), because you open on button1 click, and it, of coure ends its lifecycle togethere wit the page, an instance of which is created per request. 您实际上回答了自己:该连接未在第二个事件处理程序(Button2_click)中打开,因为您在button1上单击时打开了它,当然,它与页面一起终止了其生命周期,该页面的实例是根据请求创建的。

You can save the opened connection in a static variable (if you dont mind the connection being shared application - wide for all the users), but i really am not sure you souldnt really just go with the code you posted in your edit. 您可以将打开的连接保存在一个静态变量中(如果您不介意该连接为共享应用程序-适用于所有用户),但我不确定您是否真的会使用您在编辑中发布的代码。
if you want the connectoin to be availibale application wide, define its variable as a static one (but make sure you initialize / connect before the first attempt to use), You can use the Lazy<T> helper classes provided in .net 4 to make sure the connection is initialized once, only on the first time it is needed. 如果您希望connectoin在整个应用程序范围内都可用,请将其变量定义为静态变量(但请确保在首次尝试使用之前进行初始化/连接),可以使用.net 4中提供的Lazy<T> helper类来确保仅在第一次需要连接时初始化一次。
If you need the connection to be accessible in other classes as well, you can create a seaparate singleton class to wrap it (and initialize it there, in a same way) 如果您还需要在其他类中也可以访问该连接,则可以创建一个seaparate单例类来包装它(并以相同的方式在那里初始化它)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM