Search code examples
c#socketstcpstreamudp

Live Radio With UDP TCP Protocols


using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace NetworkProgramming
{
    public class IPEndPointSample
    {
       
            public static void Main()
            {
                IPAddress host = IPAddress.Parse("149.6.43.235");
                IPEndPoint hostep = new IPEndPoint(host, 443);
                Socket sock = new Socket(AddressFamily.InterNetwork,
                SocketType.Stream, ProtocolType.Tcp);
                try
                {
                    sock.Connect(hostep);
                }
                catch (SocketException e)
                {
                    Console.WriteLine("Problem connecting to host");
                    Console.WriteLine(e.ToString());
                    sock.Close();
                    return;
                }
                try
                {
                    sock.Send(Encoding.ASCII.GetBytes("testing"));
                }
                catch (SocketException e)
                {
                    Console.WriteLine("Problem sending data");
                    Console.WriteLine(e.ToString());
                    sock.Close();
                    return;
                }
                sock.Close();
            }
        }
}

I want to make a live radio using the ip and port information in this xml

https://github.com/learnergthb/TcpUdpProtocolsConnection-XmlFileRead/blob/main/XMLFile1.xml

 string HostName = Dns.GetHostName();
   Console.WriteLine("Host Name of machine =" + "21303.live.streamtheworld.com"); 
    IPAddress[] ipaddress = Dns.GetHostAddresses("21303.live.streamtheworld.com");
   Console.WriteLine("IP Address of Machine is");
  foreach (IPAddress ip in ipaddress)
   {
        Console.WriteLine(ip.ToString());
    }

I converted 21303.live.streamtheworld.com <-149.6.43.235->.

When I run it it gives no results no error. What should I do for the radio to work? THANKS EVERYONE:)

!!!UPDATE!!!

//port 443
    using System;
    using System.Text;
    using System.Net;
    using System.Net.Sockets;
    
    public class Program
    {
        public static void Main()
        {
            using var client = new TcpClient();
    
            var hostname = "21303.live.streamtheworld.com";
            client.Connect(hostname,443);
            using NetworkStream networkStream = client.GetStream();
            networkStream.ReadTimeout = 2000;
    
            var message = "\nHost: 21303.live.streamtheworld.com\r\n\n\r\n";
    
            Console.WriteLine(message);
    
            using var reader = new StreamReader(networkStream, Encoding.UTF8);
    
            byte[] bytes = Encoding.UTF8.GetBytes(message);
            networkStream.Write(bytes, 0, bytes.Length);
    
            Console.WriteLine(reader.ReadToEnd());
    
        }
        
    }

NEW UPDATE

using NAudio.Wave;
using System.Net;
using System.Net.Sockets;

namespace tcpnadudio
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            using var client = new TcpClient();

            var hostname = "21303.live.streamtheworld.com";
            client.Connect(hostname, 443);
            using NetworkStream networkStream = client.GetStream();
            Stream ms = new MemoryStream();

            PlayMp3FromUrl("21303.live.streamtheworld.com");

            void PlayMp3FromUrl(string url)
            {
                new Thread(delegate (object o)
                {
                    var response = WebRequest.Create(url).GetResponse();
                    using (var stream = response.GetResponseStream())
                    {
                        byte[] buffer = new byte[65536]; // 64KB chunks
                        int read;
                        while ((read = stream.Read(buffer, 0, buffer.Length)) > 0)
                        {
                            var pos = ms.Position;
                            ms.Position = ms.Length;
                            ms.Write(buffer, 0, read);
                            ms.Position = pos;
                        }
                    }
                }).Start();

                // Pre-buffering some data to allow NAudio to start playing
                while (ms.Length < 65536 * 10)
                    Thread.Sleep(1000);

                ms.Position = 0;
                using (WaveStream blockAlignedStream = new BlockAlignReductionStream(WaveFormatConversionStream.CreatePcmStream(new Mp3FileReader(ms))))
                {
                    using (WaveOut waveOut = new WaveOut(WaveCallbackInfo.FunctionCallback()))
                    {
                        waveOut.Init(blockAlignedStream);
                        waveOut.Play();
                        while (waveOut.PlaybackState == PlaybackState.Playing)
                        {

 
 
                             System.Threading.Thread.Sleep(100);
                        }
                    }
                }
            }
        }
    }
}

ERROR:new try

new error

************************** NEW UPDATE WITH SHAZAM ******************

using Microsoft.AspNet.SignalR;
using NAudio.Wave;
using System.Net;
using System.Net.Http.Headers;
using System.Net.Sockets;

namespace RadioStream
{
    public partial class Form1 : Form
    {
        private IHubContext<byte[]> _hubContext;

        public Form1()
        {
            InitializeComponent();
        }
          
        private void  Form1_LoadAsync(object sender, EventArgs e)
        {
            Stream ms = new MemoryStream();

            PlayMp3FromUrl("http://21303.live.streamtheworld.com/METRO_FM_SC");

            async void PlayMp3FromUrl(string url)
            {
                new Thread(delegate (object o)
                {
                    var response = WebRequest.Create(url).GetResponse();
                    using (var stream = response.GetResponseStream())
                    {
                        byte[] buffer = new byte[65536]; // 64KB chunks
                        int read;
                        while ((read = stream.Read(buffer, 0, buffer.Length)) > 0)
                        {
                            var pos = ms.Position;
                            ms.Position = ms.Length;
                            ms.Write(buffer, 0, read);
                            ms.Position = pos;
                        }
                    }
                }).Start();

                // Pre-buffering some data to allow NAudio to start playing
                while (ms.Length < 65536 * 10)
                    Thread.Sleep(1000);

                ms.Position = 0;
                using (WaveStream blockAlignedStream = new BlockAlignReductionStream(WaveFormatConversionStream.CreatePcmStream(new Mp3FileReader(ms))))
                {
                    using (WaveOut waveOut = new WaveOut(WaveCallbackInfo.FunctionCallback()))
                    {
                        waveOut.Init(blockAlignedStream);
                        waveOut.Play();
                        while (waveOut.PlaybackState == PlaybackState.Playing)
                        {

                            //readonly IHubContext<Stream> _hubContext;
                            async Task Channel(IHubContext<byte[]> hubContext)
                            {
                                _hubContext = hubContext;
                            }
                            //public async Task Stream(string byte[])
                            //{
                            //    _hubContext.Clients.All.SendAsync("RadioStream", byteArray[]);
                            //}


                            
                        var client = new HttpClient();
                        var request = new HttpRequestMessage
                        {
                            Method = HttpMethod.Get,
                            RequestUri = new Uri("https://shazam.p.rapidapi.com/songs/get-details?key=-------=en-US"),
                            Headers =
{
    { "X-RapidAPI-Key", "--------------" },
    { "X-RapidAPI-Host", "shazam.p.rapidapi.com" },
},
                        };
                        using (var response = await client.SendAsync(request))
                        {
                            response.EnsureSuccessStatusCode();
                            var body = await response.Content.ReadAsStringAsync();
                            Console.WriteLine(body);
                        }// SHAZAM API
                        }

                        System.Threading.Thread.Sleep(100);
                        
                    }
                }
            }
            
        }
    }

}

StreamHub.cs

using Microsoft.AspNet.SignalR;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RadioStream.Hubs
{
    
        public class StreamHub : Hub
        {
            public async Task Stream(string bytee)
            {
                await Clients.All.SendAsync("RadioStream", bytee);
            }
        }
}

internal_server_error_shazam


Solution

  • Following will get the URLs of the stream. You can put the URL into a browser URL to hear the results so you can test that it works. Then write c# code. If you replace the HTTP with HTTS you will get the port 443 instead of 80/3690:

    using System;
    using System.Linq;
    using System.Text;
    using System.Collections;
    using System.Collections.Generic;
    using System.Net;
    using System.Net.Sockets;
    using System.IO;
    
    namespace ConsoleApp2
    {
        class Program
        {
    
            const string URL = "http://playerservices.streamtheworld.com/pls/METRO_FM.pls";
            static void Main(string[] args)
            {
                WebRequest request = HttpWebRequest.Create(URL); 
       
                request.Headers.Add(HttpRequestHeader.UserAgent, "Mozilla / 5.0(Windows NT 10.0; Win64; x64) AppleWebKit / 537.36(KHTML, like Gecko) Chrome / 103.0.0.0 Safari / 537.36");
                request.Headers.Add(HttpRequestHeader.Accept, "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9");
                request.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip, deflate");
                request.Headers.Add(HttpRequestHeader.AcceptLanguage, "en-US,en;q=0.9");
                WebResponse response =  request.GetResponse();
    
    
                Stream stream = response.GetResponseStream();
                StreamReader sReader = new StreamReader(stream);
    
                List<string> urls = new List<string>();
                string line = "";
                while((line = sReader.ReadLine()) != null)
                {
                    line = line.Trim();
                    if (line.StartsWith("File") && line.Contains("="))
                    {
                        string[] splitLine = line.Split(new char[] { '=' });
                        urls.Add(splitLine[1]);
                        Console.WriteLine(splitLine[1]);
    
                    }
                }
                Console.ReadLine();
            }
    
        }
     
    }