1
0
mirror of https://github.com/ZetaKebab/MpcNET.git synced 2025-01-14 22:18:43 +00:00

MpcConnection small cleanup

This commit is contained in:
Gabriel 2016-11-01 10:04:31 +01:00
parent dd938883e5
commit 0314746dff

View File

@ -1,21 +1,3 @@
/*
* Copyright 2008 Matthias Sessler
*
* This file is part of LibMpc.net.
*
* LibMpc.net is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 2.1 of the License, or
* (at your option) any later version.
*
* LibMpc.net is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with LibMpc.net. If not, see <http://www.gnu.org/licenses/>.
*/
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Collections.ObjectModel; using System.Collections.ObjectModel;
@ -27,11 +9,6 @@ using System.Text.RegularExpressions;
namespace Libmpc namespace Libmpc
{ {
/// <summary>
/// The delegate for the <see cref="MpcConnection.OnConnected"/> and <see cref="MpcConnection.OnDisconnected"/> events.
/// </summary>
/// <param name="connection">The connection firing the event.</param>
public delegate void MpcConnectionEventDelegate( MpcConnection connection );
/// <summary> /// <summary>
/// Keeps the connection to the MPD server and handels the most basic structure of the /// Keeps the connection to the MPD server and handels the most basic structure of the
/// MPD protocol. The high level commands are handeled in the <see cref="Libmpc.Mpc"/> /// MPD protocol. The high level commands are handeled in the <see cref="Libmpc.Mpc"/>
@ -42,11 +19,11 @@ namespace Libmpc
/// <summary> /// <summary>
/// Is fired when a connection to a MPD server is established. /// Is fired when a connection to a MPD server is established.
/// </summary> /// </summary>
public event MpcConnectionEventDelegate OnConnected; public event EventHandler OnConnected;
/// <summary> /// <summary>
/// Is fired when the connection to the MPD server is closed. /// Is fired when the connection to the MPD server is closed.
/// </summary> /// </summary>
public event MpcConnectionEventDelegate OnDisconnected; public event EventHandler OnDisconnected;
private static readonly string FIRST_LINE_PREFIX = "OK MPD "; private static readonly string FIRST_LINE_PREFIX = "OK MPD ";
@ -55,58 +32,58 @@ namespace Libmpc
private static readonly Regex ACK_REGEX = new Regex("^ACK \\[(?<code>[0-9]*)@(?<nr>[0-9]*)] \\{(?<command>[a-z]*)} (?<message>.*)$"); private static readonly Regex ACK_REGEX = new Regex("^ACK \\[(?<code>[0-9]*)@(?<nr>[0-9]*)] \\{(?<command>[a-z]*)} (?<message>.*)$");
private IPEndPoint ipEndPoint = null; private IPEndPoint _ipEndPoint;
private TcpClient tcpClient = null; private TcpClient _tcpClient;
private NetworkStream networkStream = null; private NetworkStream _networkStream;
private StreamReader reader; private StreamReader _reader;
private StreamWriter writer; private StreamWriter _writer;
private string version; private string _version;
/// <summary> /// <summary>
/// If the connection to the MPD is connected. /// If the connection to the MPD is connected.
/// </summary> /// </summary>
public bool Connected { get { return (this.tcpClient != null) && this.tcpClient.Connected; } } public bool Connected { get { return (_tcpClient != null) && _tcpClient.Connected; } }
/// <summary> /// <summary>
/// The version of the MPD. /// The version of the MPD.
/// </summary> /// </summary>
public string Version { get { return this.version; } } public string Version { get { return _version; } }
private bool autoConnect = false; private bool _autoConnect = false;
/// <summary> /// <summary>
/// If a connection should be established when a command is to be /// If a connection should be established when a command is to be
/// executed in disconnected state. /// executed in disconnected state.
/// </summary> /// </summary>
public bool AutoConnect public bool AutoConnect
{ {
get{ return this.autoConnect; } get{ return _autoConnect; }
set { this.autoConnect = value; } set { _autoConnect = value; }
} }
/// <summary>
/// Creates a new MpdConnection.
/// </summary>
public MpcConnection() {}
/// <summary> /// <summary>
/// Creates a new MpdConnection. /// Creates a new MpdConnection.
/// </summary> /// </summary>
/// <param name="server">The IPEndPoint of the MPD server.</param> /// <param name="server">The IPEndPoint of the MPD server.</param>
public MpcConnection(IPEndPoint server) { this.Connect(server); } public MpcConnection(IPEndPoint server)
{
Connect(server);
}
/// <summary> /// <summary>
/// The IPEndPoint of the MPD server. /// The IPEndPoint of the MPD server.
/// </summary> /// </summary>
/// <exception cref="AlreadyConnectedException">When a conenction to a MPD server is already established.</exception> /// <exception cref="AlreadyConnectedException">When a conenction to a MPD server is already established.</exception>
public IPEndPoint Server public IPEndPoint Server
{ {
get { return this.ipEndPoint; } get { return _ipEndPoint; }
set set
{ {
if (this.Connected) if (Connected)
throw new AlreadyConnectedException(); throw new AlreadyConnectedException();
this.ipEndPoint = value; _ipEndPoint = value;
this.ClearConnectionFields(); ClearConnectionFields();
} }
} }
/// <summary> /// <summary>
@ -115,8 +92,8 @@ namespace Libmpc
/// <param name="server">The IPEndPoint of the server.</param> /// <param name="server">The IPEndPoint of the server.</param>
public void Connect(IPEndPoint server) public void Connect(IPEndPoint server)
{ {
this.Server = server; Server = server;
this.Connect(); Connect();
} }
/// <summary> /// <summary>
/// Connects to the MPD server who's IPEndPoint was set in the Server property. /// Connects to the MPD server who's IPEndPoint was set in the Server property.
@ -124,51 +101,51 @@ namespace Libmpc
/// <exception cref="InvalidOperationException">If no IPEndPoint was set to the Server property.</exception> /// <exception cref="InvalidOperationException">If no IPEndPoint was set to the Server property.</exception>
public void Connect() public void Connect()
{ {
if (this.ipEndPoint == null) if (_ipEndPoint == null)
throw new InvalidOperationException("Server IPEndPoint not set."); throw new InvalidOperationException("Server IPEndPoint not set.");
if (this.Connected) if (Connected)
throw new AlreadyConnectedException(); throw new AlreadyConnectedException();
this.tcpClient = new TcpClient(
this.ipEndPoint.Address.ToString(),
this.ipEndPoint.Port);
this.networkStream = this.tcpClient.GetStream();
this.reader = new StreamReader(this.networkStream, Encoding.UTF8); _tcpClient = new TcpClient();
this.writer = new StreamWriter(this.networkStream, Encoding.UTF8); var connection = _tcpClient.ConnectAsync(_ipEndPoint.Address, _ipEndPoint.Port);
this.writer.NewLine = "\n"; connection.Wait();
string firstLine = this.reader.ReadLine(); _networkStream = _tcpClient.GetStream();
_reader = new StreamReader(_networkStream, Encoding.UTF8);
_writer = new StreamWriter(_networkStream, Encoding.UTF8);
_writer.NewLine = "\n";
string firstLine = _reader.ReadLine();
if( !firstLine.StartsWith( FIRST_LINE_PREFIX ) ) if( !firstLine.StartsWith( FIRST_LINE_PREFIX ) )
{ {
this.Disconnect(); Disconnect();
throw new InvalidDataException("Response of mpd does not start with \"" + FIRST_LINE_PREFIX + "\"." ); throw new InvalidDataException("Response of mpd does not start with \"" + FIRST_LINE_PREFIX + "\"." );
} }
this.version = firstLine.Substring(FIRST_LINE_PREFIX.Length); _version = firstLine.Substring(FIRST_LINE_PREFIX.Length);
this.writer.WriteLine(); _writer.WriteLine();
this.writer.Flush(); _writer.Flush();
this.readResponse(); ReadResponse();
if( this.OnConnected != null ) OnConnected?.Invoke(this, EventArgs.Empty);
this.OnConnected.Invoke( this );
} }
/// <summary> /// <summary>
/// Disconnects from the current MPD server. /// Disconnects from the current MPD server.
/// </summary> /// </summary>
public void Disconnect() public void Disconnect()
{ {
if (this.tcpClient == null) if (_tcpClient == null)
return; return;
this.networkStream.Close(); _networkStream.Dispose();
this.ClearConnectionFields(); ClearConnectionFields();
if( this.OnDisconnected != null ) OnDisconnected?.Invoke(this, EventArgs.Empty);
this.OnDisconnected.Invoke( this );
} }
/// <summary> /// <summary>
/// Executes a simple command without arguments on the MPD server and returns the response. /// Executes a simple command without arguments on the MPD server and returns the response.
@ -185,18 +162,18 @@ namespace Libmpc
if (command.Contains("\n")) if (command.Contains("\n"))
throw new ArgumentException("command contains newline"); throw new ArgumentException("command contains newline");
this.CheckConnected(); CheckConnected();
try try
{ {
this.writer.WriteLine(command); _writer.WriteLine(command);
this.writer.Flush(); _writer.Flush();
return this.readResponse(); return ReadResponse();
} }
catch (Exception) catch (Exception)
{ {
try { this.Disconnect(); } try { Disconnect(); }
catch (Exception) { } catch (Exception) { }
throw; throw;
} }
@ -227,34 +204,34 @@ namespace Libmpc
throw new ArgumentException("argument[" + i + "] contains newline"); throw new ArgumentException("argument[" + i + "] contains newline");
} }
this.CheckConnected(); CheckConnected();
try try
{ {
this.writer.Write(command); _writer.Write(command);
foreach (string arg in argument) foreach (string arg in argument)
{ {
this.writer.Write(' '); _writer.Write(' ');
this.WriteToken(arg); WriteToken(arg);
} }
this.writer.WriteLine(); _writer.WriteLine();
this.writer.Flush(); _writer.Flush();
return this.readResponse(); return ReadResponse();
} }
catch (Exception) catch (Exception)
{ {
try { this.Disconnect(); } catch (Exception) { } try { Disconnect(); } catch (Exception) { }
throw; throw;
} }
} }
private void CheckConnected() private void CheckConnected()
{ {
if (!this.Connected) if (!Connected)
{ {
if (this.autoConnect) if (_autoConnect)
this.Connect(); Connect();
else else
throw new NotConnectedException(); throw new NotConnectedException();
} }
@ -265,25 +242,25 @@ namespace Libmpc
{ {
if (token.Contains(" ")) if (token.Contains(" "))
{ {
this.writer.Write("\""); _writer.Write("\"");
foreach (char chr in token) foreach (char chr in token)
if (chr == '"') if (chr == '"')
this.writer.Write("\\\""); _writer.Write("\\\"");
else else
this.writer.Write(chr); _writer.Write(chr);
} }
else else
this.writer.Write(token); _writer.Write(token);
} }
private MpdResponse readResponse() private MpdResponse ReadResponse()
{ {
List<string> ret = new List<string>(); List<string> ret = new List<string>();
string line = this.reader.ReadLine(); string line = _reader.ReadLine();
while (!(line.Equals(OK) || line.StartsWith(ACK))) while (!(line.Equals(OK) || line.StartsWith(ACK)))
{ {
ret.Add(line); ret.Add(line);
line = this.reader.ReadLine(); line = _reader.ReadLine();
} }
if (line.Equals(OK)) if (line.Equals(OK))
return new MpdResponse(new ReadOnlyCollection<string>(ret)); return new MpdResponse(new ReadOnlyCollection<string>(ret));
@ -306,11 +283,11 @@ namespace Libmpc
private void ClearConnectionFields() private void ClearConnectionFields()
{ {
this.tcpClient = null; _tcpClient?.Dispose();
this.networkStream = null; _networkStream?.Dispose();
this.reader = null; _reader?.Dispose();
this.writer = null; _writer?.Dispose();
this.version = null; _version = string.Empty;
} }
} }
} }