在ASP.net TCP客户端 [英] TCP client in ASP.net

查看:120
本文介绍了在ASP.net TCP客户端的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图从ASP Web应用程序连接到TCP服务器。我这样做是使用应用程序在C#中,现在我想看看它是否会从Web浏览器的工作。

我的code是:

 使用系统;
使用System.Collections.Generic;
使用System.Linq的;
使用的System.Web;
使用System.Web.UI程序;
使用System.Web.UI.WebControls;
使用System.ComponentModel;
使用System.Data这;
使用System.Drawing中;
使用System.Text;
使用System.Net;
使用的System.Net.Sockets;

命名空间TcpWebClient

{
    公共部分类_Default:System.Web.UI.Page
{

    私人byte []的数据=新的字节[1024];
    IPEndPoint IPEP =新IPEndPoint(
            IPAddress.Parse(192.168.1.20),12000);

    套接字服务器=新的Socket(AddressFamily.InterNetwork,
                   SocketType.Stream,ProtocolType.Tcp);


    保护无效的Page_Load(对象发件人,EventArgs的)
    {

    }

    保护无效的button1_Click(对象发件人,EventArgs的)
    {

        尝试
        {
            server.Connect(IPEP);
        }
        赶上(SocketException)
        {
        }
    }

    保护无效Button2_Click(对象发件人,EventArgs的)
    {
        的NetworkStream NS =新的NetworkStream(服务器);

        如果(ns.CanWrite)
        {
            ns.Write(Encoding.ASCII.GetBytes(DI),0,2);
            ns.Flush();
        }
        其他
        {
        }
        TextBox1.Text = NULL;
        TextBox1.Text = Encoding.ASCII.GetString(数据,0,ns.Read(数据,0,data.Length));
    }

}
}
 

什么是工作?:我有连接TCP服务器。但是,当我想要发送和接收的一些数据我得到的错误:

  IOException异常是未处理由用户code和像这样的东西:操作不支持连接的套接字(不知道是不是我的翻译为英语就可以了)。
 

我在做什么错了?

有一个第一次机会异常的类型'System.IO.IOException'的System.dll中发生

编辑:

这样的事情是工作..但计时器的每个替我需要重新连接到服务器..是有可能有一个连接,定时器读那么每刻度/发送数据,而无需重新连接?

 保护无效Timer1_Tick(对象发件人,EventArgs的)
    {

            server.Connect(IPEP);
            的NetworkStream流=新的NetworkStream(服务器);

            字节[]数据= System.Text.Encoding.ASCII.GetBytes(数据);
            stream.Write(数据,0,data.Length);
            数据=新的字节[256];
            INT32字节= stream.Read(数据,0,8);
            responseData = System.Text.Encoding.ASCII.GetString(数据,0,字节);
            TextBox1.Text = responseData;
            server.Close();

        }
 

解决方案

您居然回答自己:连接不openned在你的第二个事件处理程序(Button2_click),因为你开的按钮1单击,并,对课的结束其生命周期togethere机智的页面,它的实例每个请求被创建。

您可以保存在静态变量已打开的连接(如果你不介意的连接被共享的应用程序 - 广泛的所有用户),但我真的不知道你souldnt真的只是去与code你贴在您的编辑。
如果你想connectoin是availibale应用广泛,定义其变量作为一个静态的(但要确保你初始化/连接之前,第一次尝试使用),您可以使用延迟< T> 助手在.NET 4提供的类以确保连接初始化一次,只在第一次是必要的。
如果您需要的连接,可以在其他类访问,以及,你可以创建一个seaparate单独的类来包装它(并初始化它在那里,在一个同样的方式)

i'm trying to connect from asp web application to tcp server. I did this using application in C#, and now i'd like to see if it will be working from web browser.

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

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.

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

这篇关于在ASP.net TCP客户端的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆