asternet/Asterisk.2013/Asterisk.NET/FastAGI/AGIReader.cs

90 lines
2.6 KiB
C#
Raw Normal View History

using System.Collections.Generic;
2015-01-03 15:37:29 +00:00
using System.IO;
using AsterNET.IO;
2014-01-08 14:16:39 +00:00
namespace AsterNET.FastAGI
{
2015-01-03 15:37:29 +00:00
public class AGIReader
{
#if LOGGER
2015-01-03 15:37:29 +00:00
private readonly Logger logger = Logger.Instance();
#endif
2015-01-03 15:37:29 +00:00
private readonly SocketConnection socket;
public AGIReader(SocketConnection socket)
{
this.socket = socket;
}
2015-01-03 15:37:29 +00:00
public AGIRequest ReadRequest()
{
var lines = new List<string>();
try
{
#if LOGGER
2015-01-03 15:37:29 +00:00
logger.Info("AGIReader.ReadRequest():");
#endif
2015-01-03 15:37:29 +00:00
string line;
while ((line = socket.ReadLine()) != null)
{
if (line.Length == 0)
break;
lines.Add(line);
#if LOGGER
2015-01-03 15:37:29 +00:00
logger.Info(line);
#endif
2015-01-03 15:37:29 +00:00
}
}
catch (IOException ex)
{
throw new AGINetworkException("Unable to read request from Asterisk: " + ex.Message, ex);
}
2015-01-03 15:37:29 +00:00
var request = new AGIRequest(lines)
{
LocalAddress = socket.LocalAddress,
LocalPort = socket.LocalPort,
RemoteAddress = socket.RemoteAddress,
RemotePort = socket.RemotePort
};
2015-01-03 15:37:29 +00:00
return request;
}
2015-01-03 15:37:29 +00:00
public AGIReply ReadReply()
{
string line;
var badSyntax = ((int) AGIReplyStatuses.SC_INVALID_COMMAND_SYNTAX).ToString();
2015-01-03 15:37:29 +00:00
var lines = new List<string>();
try
{
line = socket.ReadLine();
}
catch (IOException ex)
{
throw new AGINetworkException("Unable to read reply from Asterisk: " + ex.Message, ex);
}
if (line == null)
throw new AGIHangupException();
2015-01-03 15:37:29 +00:00
lines.Add(line);
// read synopsis and usage if statuscode is 520
if (line.StartsWith(badSyntax))
try
{
while ((line = socket.ReadLine()) != null)
{
lines.Add(line);
if (line.StartsWith(badSyntax))
break;
}
}
catch (IOException ex)
{
throw new AGINetworkException("Unable to read reply from Asterisk: " + ex.Message, ex);
}
return new AGIReply(lines);
}
}
}