BASS.NET API for the Un4seen BASS Audio LibraryStreamingServer ClassBASS.NET API for the Un4seen BASS Audio Library
Base class for all streaming server classes (e.g. SHOUTcast or ICEcast).
Inheritance Hierarchy

SystemObject
  Un4seen.Bass.MiscStreamingServer
    Un4seen.Bass.MiscICEcast
    Un4seen.Bass.MiscSHOUTcast
    Un4seen.Bass.MiscWMAcast

Namespace: Un4seen.Bass.Misc
Assembly: Bass.Net (in Bass.Net.dll) Version: 2.4.12.0
Syntax

[SerializableAttribute]
public abstract class StreamingServer : IStreamingServer

The StreamingServer type exposes the following members.

Constructors

  NameDescription
Public methodStreamingServer(IBaseEncoder)
Default constructor, creating an instance for a streaming server implementation (using BASSenc as the default processor).
Public methodStreamingServer(IBaseEncoder, Boolean)
Default constructor, creating an instance for a streaming server implementation.
Top
Properties

  NameDescription
Public propertyEncoder
Returns the encoder interface which is used with this instance.
Public propertyForceUTF8TitleUpdates
Gets or Sets if title updates (via UpdateTitle(String, String)) should in any case use UTF-8 (default is ).
Public propertyIsConnected
Returns , if connected to a boadcast server - else .
Public propertyLastError
Gets or Sets the last streaming error.
Public propertyLastErrorMessage
Gets or Sets the last streaming error message.
Public propertySongTitle
The current/last song title.
Public propertySongUrl
The current/last song url.
Public propertyUseBASS
Gets if native BASSenc should be used to connect and stream to the server (as specified in the constructor).
Top
Methods

  NameDescription
Public methodConnect
Connects to a streaming server.
Public methodDisconnect
Disconnects from a streaming server.
Public methodDispose
Implement IDisposable.
Protected methodFinalize
Finalization code.
(Overrides ObjectFinalize.)
Protected methodStatic memberGetIPfromHost
Resolved a given host name (DNS or IP) to its possible IP addesses.
Public methodGetListeners
Returns the number of listeners currently connected.
Public methodGetStats
Returns the XML stats of the server.
Public methodLogin
Performs a login to and/or initializes the streaming server.
Public methodSendData
Sends encoded sample data (manually) to the streaming server (e.g. the data as received in an own ENCODEPROC).
Public methodUpdateTitle(String, String)
Updates the song title of the streaming server.
Public methodUpdateTitle(TAG_INFO, String)
Updates the song title of the streaming server.
Top
Remarks

This base class is not intended for direct use, but defines all abstract properties and methods which needs to be implemented by an actual streaming server class. A derived class must implement: IsConnected, Connect, Disconnect, Login, SendData(IntPtr, Int32) and UpdateTitle(String, String).

The properties Encoder, LastError and LastErrorMessage have been already implemented.

You might use this base class to derive your own streaming server implementations.

If an instance of a derived class is being disposed, an already created connection to a streaming server will automatically be closed (using Disconnect) and an Encoder will be stopped, if active.

Examples

This example shows a basic implementation of an own streaming server class:
VB
Public Class MyOwnServer Inherits StreamingServer

    ' Constructor
    Public Sub New(encoder As IBaseEncoder, useBASS As Boolean) MyBase.New(encoder, useBASS)
      ' validity check
      If encoder.EncoderType <> BASSChannelType.BASS_CTYPE_STREAM_MP3 AndAlso 
         encoder.EncoderType <> BASSChannelType.BASS_CTYPE_STREAM_AAC Then
         Throw New Exception("Invalid EncoderType (only MP3 and AAC is supported)!")
      End If
    End Sub

    Private _socket As Socket = Nothing
    Private _loggedIn As Boolean = False
    Private _data As Byte() = Nothing
    Private _lock As Object = False
    Public ServerAddress As String = "localhost"
    Public ServerPort As Integer = 8000

    Public Overrides ReadOnly Property IsConnected() As Boolean
      Get
        If Not (_socket Is Nothing) Then
          Return _socket.Connected AndAlso _loggedIn
        Else
          Return False
        End If
      End Get
    End Property

    Public Overrides Function Connect() As Boolean
      ' check the encoder
      If Not Encoder.IsActive Then
        LastError = STREAMINGERROR.Error_EncoderError
        LastErrorMessage = "Encoder not active!"
        Return False
      End If
      ' close any connections, if still open
      If Not (_socket Is Nothing) AndAlso _socket.Connected Then
        _socket.Close()
        _socket = Nothing
      End If
      ' create a connection at port+1
      _socket = CreateSocket(ServerAddress, ServerPort + 1)
      Return Not (_socket Is Nothing) AndAlso _socket.Connected
    End Function

    Public Overrides Function Disconnect() As Boolean
      Dim ok As Boolean = False
      Try
        _socket.Close()
      Catch
      Finally
        If Not (_socket Is Nothing) AndAlso _socket.Connected Then
          LastError = STREAMINGERROR.Error_Disconnect
          LastErrorMessage = "Winsock error: " + 
                             Convert.ToString(System.Runtime.InteropServices.Marshal.GetLastWin32Error())
        Else
          ok = True
          _socket = Nothing
          _loggedIn = False
        End If
      End Try
      Return ok
    End Function

    Public Overrides Function Login() As Boolean
      If _socket Is Nothing Then
        LastError = STREAMINGERROR.Error_NotConnected
        LastErrorMessage = "Not connected to server."
        Return False
      End If
      Dim ok As Boolean = False
      If MyLogin() Then
        If MyInit() Then
          ok = True
          _loggedIn = True
          LastError = STREAMINGERROR.Ok
          LastErrorMessage = [String].Empty
        Else
          LastError = STREAMINGERROR.Error_Login
          LastErrorMessage = "Server could not be initialized."
        End If
      Else
        LastError = STREAMINGERROR.Error_Login
        LastErrorMessage = "Invalid username or password."
      End If
      Return ok
    End Function

    Public Overrides Function SendData(buffer As IntPtr, length As Integer) As Integer
      If buffer = IntPtr.Zero OrElse length = 0 Then
        Return 0
      End If
      Dim sendData As Integer = -1
      Try
        SyncLock _lock
        ' dynamic buffer allocation
        If _data Is Nothing OrElse _data.Length < length Then
          _data = New Byte(length) {}
        End If
        Marshal.Copy(buffer, _data, 0, length)
        sendData = _socket.Send(_data, 0, length, SocketFlags.None)
        If sendData < 0 Then
          LastError = STREAMINGERROR.Error_SendingData
          LastErrorMessage = [String].Format("{0} bytes not send.", length)
          Disconnect()
        Else
          If sendData <> length Then
            LastError = STREAMINGERROR.Warning_LessDataSend
            LastErrorMessage = [String].Format("{0} of {1} bytes send.", sendData, length)
          End If
        End If
      End SyncLock
      Catch e As Exception
        LastError = STREAMINGERROR.Error_SendingData
        LastErrorMessage = e.Message
        sendData = -1
        Disconnect()
      End Try
      Return sendData
    End Function

    Public Overrides Function UpdateTitle(song As String) As Boolean
      SongTitle = song
      Return MyUpdateTitle(song)
    End Function

    Private Function CreateSocket(serveraddress As String, port As Integer) As Socket
      Dim socket As Socket = Nothing
      Dim hostEntry As IPHostEntry = Nothing
      Try
        ' Get host related information
        hostEntry = Dns.GetHostEntry(serveraddress)
        ' Loop through the AddressList to obtain the supported AddressFamily.
        Dim address As IPAddress
        For Each address In hostEntry.AddressList
          Try
            Dim ipe As New IPEndPoint(address, port)
            Dim tempSocket As New Socket(ipe.AddressFamily, SocketType.Stream, ProtocolType.Tcp)
            tempSocket.Connect(ipe)
            If tempSocket.Connected Then
              socket = tempSocket
              Exit ForEach
            Else
              GoTo ContinueForEach1
            End If
          Catch e As Exception
            LastError = STREAMINGERROR.Error_CreatingConnection
            LastErrorMessage = e.Message
            socket = Nothing
          End Try
          ContinueForEach1:
        Next address
      Catch e As Exception
        LastError = STREAMINGERROR.Error_ResolvingServerAddress
        LastErrorMessage = e.Message
        socket = Nothing
      End Try
      Return socket
    End Function

    Private Function MyLogin() As Boolean
      If _socket Is Nothing Then
        Return False
      End If 
      ' e.g. send password here using the "_socket"
      ...
    End Function

    Private Function MyInit() As Boolean
      If _socket Is Nothing Then
        Return False
      End If 
      ' e.g. send some init data to the server here using the "_socket"
      ...
    End Function

    Private Function MyUpdateTitle(song As String) As Boolean
      Dim ok As Boolean = False
      Dim socket As Socket = Nothing
      Try
        socket = CreateSocket(ServerAddress, ServerPort)
        If Not (socket Is Nothing) Then
          ' send the song title using the created "socket"
          ...
          ok = True
        End If
      Catch
      Finally
        ' disconnect
        If Not (socket Is Nothing) Then
          socket.Close()
          socket = Nothing
        End If
      End Try
      Return ok
    End Function

End Class
public class MyOwnServer : StreamingServer
{
    // Constructor
    public MyOwnServer(IBaseEncoder encoder, bool useBASS) : base(encoder, useBASS)
    {
      // validity check
      if (encoder.EncoderType != BASSChannelType.BASS_CTYPE_STREAM_MP3 &&
          encoder.EncoderType != BASSChannelType.BASS_CTYPE_STREAM_AAC)
        throw new Exception( "Invalid EncoderType (only MP3 and AAC is supported)!" );
    }

    private Socket _socket = null;
    private bool _loggedIn = false;
    private byte[] _data = null;
    private object _lock = false;
    public string ServerAddress = "localhost";
    public int ServerPort = 8000;

    public override bool IsConnected
    {
      get
      {
        if (_socket != null)
          return _socket.Connected && _loggedIn;
        else
          return false;
      }
    }

    public override bool Connect()
    {
      // check the encoder
      if (!Encoder.IsActive)
      {
        LastError = STREAMINGERROR.Error_EncoderError;
        LastErrorMessage = "Encoder not active!";
        return false;
      }
      // close any connections, if still open
      if (_socket != null && _socket.Connected)
      {
        _socket.Close();
        _socket = null;
      }
      // create a connection at port+1
      _socket = CreateSocket( ServerAddress, ServerPort+1 );
      return (_socket != null && _socket.Connected);
    }

    public override bool Disconnect()
    {
      bool ok = false;
      try
      {
        _socket.Close();
      }
      catch { }
      finally
      {
        if (_socket != null && _socket.Connected) 
        {
          LastError = STREAMINGERROR.Error_Disconnect;
          LastErrorMessage = "Winsock error: " + 
            Convert.ToString(System.Runtime.InteropServices.Marshal.GetLastWin32Error());
        }
        else
        {
          ok = true;
          _socket = null;
          _loggedIn = false;
        }
      }
      return ok;
    }

    public override bool Login()
    {
      if (_socket == null)
      {
        LastError = STREAMINGERROR.Error_NotConnected;
        LastErrorMessage = "Not connected to server.";
        return false;
      }
      bool ok = false;
      if ( MyLogin() )
      {
        if ( MyInit() )
        {
          ok = true;
          _loggedIn = true;
          LastError = STREAMINGERROR.Ok;
          LastErrorMessage = String.Empty;
        }
        else
        {
          LastError = STREAMINGERROR.Error_Login;
          LastErrorMessage = "Server could not be initialized.";
        }
      }
      else
      {
        LastError = STREAMINGERROR.Error_Login;
        LastErrorMessage = "Invalid username or password.";
      }
      return ok;
    }

    public override int SendData(IntPtr buffer, int length)
    {
      if (buffer == IntPtr.Zero || length == 0)
        return 0;
      int sendData = -1;
      try
      {
        lock (_lock)
        {
          // dynamic buffer allocation
          if (_data == null || _data.Length < length)
            _data = new byte[length];
          Marshal.Copy(buffer, _data, 0, length);
          sendData = _socket.Send( _data, 0, length, SocketFlags.None );
          if (sendData < 0)
          {
            LastError = STREAMINGERROR.Error_SendingData;
            LastErrorMessage = String.Format( "{0} bytes not send.", length);
            Disconnect();
          }
          else if (sendData != length)
          {
            LastError = STREAMINGERROR.Warning_LessDataSend;
            LastErrorMessage = String.Format( "{0} of {1} bytes send.", sendData, length);
          }
        }
      }
      catch (Exception e)
      { 
        LastError = STREAMINGERROR.Error_SendingData;
        LastErrorMessage = e.Message;
        sendData = -1;
        Disconnect();
      }
      return sendData;
    }

    public override bool UpdateTitle(string song, string url)
    {
      SongTitle = song;
      return MyUpdateTitle(song);
    }

    private Socket CreateSocket(string serveraddress, int port)
    {
      Socket socket = null;
      IPHostEntry hostEntry = null;
      try
      {
        // Get host related information
        hostEntry = Dns.GetHostEntry(serveraddress);
        // Loop through the AddressList to obtain the supported AddressFamily.
        foreach(IPAddress address in hostEntry.AddressList)
        {
          try
          {
            IPEndPoint ipe = new IPEndPoint(address, port);
            Socket tempSocket = new Socket(ipe.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
            tempSocket.Connect(ipe);
            if (tempSocket.Connected)
            {
              socket = tempSocket;
              break;
            }
            else
            {
              continue;
            }
          }
          catch (Exception e)
          { 
            LastError = STREAMINGERROR.Error_CreatingConnection;
            LastErrorMessage = e.Message;
            socket = null; 
          }
        }
      }
      catch (Exception e)
      { 
        LastError = STREAMINGERROR.Error_ResolvingServerAddress;
        LastErrorMessage = e.Message;
        socket = null;
      }
      return socket;
    }

    private bool MyLogin() 
    {
      if (_socket == null)
        return false;
      // e.g. send password here using the "_socket"
      ...
    }

    private bool MyInit() 
    {
      if (_socket == null)
        return false;
      // e.g. send some init data to the server here using the "_socket"
      ...
    }

    private bool MyUpdateTitle(string song)
    {
      bool ok = false;
      Socket socket = null;
      try
      {
        socket = CreateSocket( ServerAddress, ServerPort );
        if (socket != null)
        {
          // send the song title using the created "socket"
          ...
          ok = true;
        }
      }
      catch { }
      finally
      {
        // disconnect
        if (socket != null)
        {
          socket.Close();
          socket = null;
        }
      }
      return ok;
    }
}
See Also

Reference