4
Reply

How to read data from port with ASP.NET

Nitin

Nitin

Nov 24 2009 12:15 AM
6.2k

Hello
I want to read data from port of server computer with ASP.NET. My code is as follows, but throws timeout exception after reaching at line "line = COM1.ReadLine();". Can anyone pls help me to solve this issue. Or is there any other way out?
 
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO.Ports;
using System.Text;
public partial class Default2 : System.Web.UI.Page
{
    public static SerialPort COM1 = new SerialPort("COM1", 9600, System.IO.Ports.Parity.None, 8,
System.IO.Ports.StopBits.One);
protected void Page_Load(object sender, EventArgs e)
{
       if (!IsPostBack)
       {
            COM1.Handshake = Handshake.None;
            COM1.ReadTimeout = 10000;
            COM1.DtrEnable=true;
        }
    }

protected void btnWrite_Click(object sender, EventArgs e)
    {
        try
        {
            if (Session["com"] == null)
            {
                if (!COM1.IsOpen) COM1.Open();
                Session["com"] = COM1;
                COM1.WriteLine(txt_temp.Text);               
            }
            txt_temp.Text = COM1.IsOpen.ToString();
        }
        catch (Exception ex)
        {
            if (COM1.IsOpen)
                COM1.Close();
        }
    }
protected void btnRead_Click(object sender, EventArgs e)
    {
        if (Session["com"] != null)
        {
            COM1 = (SerialPort)Session["com"];
            COM1.DtrEnable = true;
            StringBuilder buffer = new StringBuilder();
            string line = "";
            try
            {
                if (!COM1.IsOpen) COM1.Open();
               
                do
                {
                    line = COM1.ReadLine(); // <-- this line throws time out exception, need to resolve this.
                   
                    if (line == null)
                        break;
                    else
                        buffer.Append(line);
                } while (true);
                txtResult.Text = buffer.ToString();
            }
            catch (Exception ex)
            {
                txtResult.Text = ex.ToString();
                if (COM1.IsOpen) COM1.Close();
                throw;
            }
            finally
            {
                if (COM1.IsOpen) COM1.Close();
            }
        }
       
    }
}

 
Thanks
Nitin

Answers (4)