Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Receive and send continuous data from TCP Socket

I'm already going crazy. So I decided to ask for help.

Scenario: In a web page, connect to the server via TCP socket, and in a loop I get the data byte by byte. These data are continuous.

Question: How do I make a WebSocket that receive and send data to the player ( html5 tag).

Default.aspx

<asp:Literal ID="ltrPlayer" runat="server" />

Default.aspx.cs

protected void Page_Load(object sender, EventArgs e)
{
    string tele = HttpContext.Current.Request.QueryString["tele"];
    string ramal = HttpContext.Current.Request.QueryString["ramal"];
    string dac = HttpContext.Current.Request.QueryString["dac"];
    string cti = HttpContext.Current.Request.QueryString["cti"];

    if ((tele != null) && (ramal != null) && (dac != null) && (cti != null))
    {
        string strAudio = "<audio controls='controls'>";
        strAudio += "<source src='Play.ashx?tele=" + tele + "&ramal=" + ramal + "&dac=" + dac + "&cti=" + cti + "' type='audio/x-wav' controls preload='auto'>";
        strAudio += "Seu browser não oferece suporte a este player.";
        strAudio += "</audio>";

        ltrPlayer.Text = strAudio;
    }
}

Play.ashx

<%@ WebHandler Language="C#" Class="Play" %>

using System;
using System.Web;

using System.Net;
using System.IO;
using Alvas.Audio; // Make the conversion VOX to WAV
using System.Media;
using System.Configuration;

using System.Net.Sockets;
using System.Text;


public class Play : IHttpHandler
{
    private NetworkStream ns;

    public void ProcessRequest(HttpContext context)
    {
        string tele = HttpContext.Current.Request.QueryString["tele"];
        string ramal = HttpContext.Current.Request.QueryString["ramal"];
        string dac = HttpContext.Current.Request.QueryString["dac"];
        string cti = HttpContext.Current.Request.QueryString["cti"];   

        if ((tele != null) && (ramal != null) && (dac != null) && (cti != null))
        {
            try
            {
                TcpClient oClient = new TcpClient();

                oClient.Connect(tele, 22000);

                ns = oClient.GetStream();
                write(ns, "ondelogar");

                ns = oClient.GetStream();
                write(ns, "monitorarRamalViaRede(tele;ramal;dac;cti)");

                Thread.Sleep(1000);                

                do
                {
                    if (oClient.GetStream().DataAvailable == true)
                    {
                        using (StringReader reader = new StringReader(read(ns)))
                        {
                            string line;

                            while ((line = reader.ReadLine()) != null)
                            {
                                Byte[] byteOut = new Byte[line.Length / 2];

                                int i = 0;
                                while (i < (line.Length / 2))
                                {
                                    byteOut[i / 2] = Convert.ToByte(line.Substring(i, 2), 16);
                                    i = i + 2;
                                }

                                Stream s = new MemoryStream(byteOut);
                                BinaryReader br = new BinaryReader(s);
                                MemoryStream pcmStream = new MemoryStream();
                                IntPtr pcmFormat = AudioCompressionManager.GetPcmFormat(1, 16, 6000);
                                WaveWriter ww = new WaveWriter(pcmStream, AudioCompressionManager.FormatBytes(pcmFormat));
                                Vox.Vox2Wav(br, ww);
                                WaveReader wr = new WaveReader(pcmStream);

                                byte[] pcmData = pcmStream.ToArray();

                                br.Close();
                                ww.Close();
                                wr.Close();
                                pcmStream.Close();
                                Array.Clear(byteOut, 0, byteOut.Length);

                                HttpContext.Current.Response.Clear();
                                HttpContext.Current.Response.AddHeader("content-disposition", string.Format("attachment; filename=\"{0}\"", "BufferDeAudio"));
                                HttpContext.Current.Response.ContentType = "audio/x-wav";
                                HttpContext.Current.Response.BinaryWrite(pcmData);
                                HttpContext.Current.Response.End();             
                            }
                        }
                    }
                }
                while (oClient.GetStream().DataAvailable == true);

                ns.Close();
            }
            catch (Exception)
            {

            }

            HttpContext.Current.Response.End();
        }
    }

    private void write(NetworkStream ns, string message)
    {
        byte[] msg = Encoding.ASCII.GetBytes(message + Environment.NewLine);
        ns.Write(msg, 0, msg.Length);
    }

    private string read(NetworkStream ns)
    {
        StringBuilder sb = new StringBuilder();

        if (ns.CanRead)
        {
            byte[] readBuffer = new byte[1024];

            int numBytesRead = 0;

            do
            {
                numBytesRead = ns.Read(readBuffer, 0, readBuffer.Length);
                sb.AppendFormat("{0}", Encoding.ASCII.GetString(readBuffer, 0, numBytesRead));
                sb.Replace(Convert.ToChar(24), ' ');
                sb.Replace(Convert.ToChar(255), ' ');
                sb.Replace('?', ' ');
            }

            while (ns.DataAvailable);
        }

        return sb.ToString();
        }                                        

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}

Then, as the loop receives the data line by line, I am sending to the player. But the only sound I hear is the last line of the loop.

I tried to put the player in a thread without success.

Is this possible? Any idea?

like image 777
Luis Henrique Avatar asked Sep 12 '26 21:09

Luis Henrique


1 Answers

You close the response stream inside your while loop. This will close the connection and interrupt the outgoing stream.

Consider something like:

HttpContext.Current.Response.Clear();
HttpContext.Current.Response.AddHeader(...))
HttpContext.Current.Response.ContentType = "audio/x-wav";

...

while ((line = reader.ReadLine()) != null)
{
    ...

    HttpContext.Current.Response.BinaryWrite(pcmData);
    HttpContext.Current.Response.Flush();
}
HttpContext.Current.Response.End();            
like image 150
Lukas Winzenried Avatar answered Sep 15 '26 11:09

Lukas Winzenried