C# Asterisk Manager Interface 实例

来源:互联网 发布:itunes mac 铃声 编辑:程序博客网 时间:2024/06/06 00:01
using System;
using System.Net;
using System.Net.Sockets;
using System.Text.RegularExpressions;
using System.Text;

namespace AsteriskPrototype
{
class AppConsole
{
[STAThread]
static void Main(string[] args)
{
Console.WriteLine("Quick and Dirty Asterisk Manager Daemon Test:\n");

// Connect to the asterisk server.
Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint serverEndPoint = new IPEndPoint(IPAddress.Parse("192.168.0.20"), 5038);
clientSocket.Connect(serverEndPoint);

// Login to the server; manager.conf needs to be setup with matching credentials.
clientSocket.Send(Encoding.ASCII.GetBytes("Action: Login\r\nUsername: mark\r\nSecret: mysecret\r\nActionID: 1\r\n\r\n"));

int bytesRead = 0;


do
{
byte[] buffer = new byte[1024];
bytesRead = clientSocket.Receive(buffer);

//Console.WriteLine(bytesRead + " bytes from asterisk server.");

string response = Encoding.ASCII.GetString(buffer, 0, bytesRead);
Console.WriteLine(response);

if(Regex.Match(response, "Message: Authentication accepted", RegexOptions.IgnoreCase).Success)
{
// Send a ping request the asterisk server will send back a pong response.
clientSocket.Send(Encoding.ASCII.GetBytes("Action: Ping\r\nActionID: 2\r\n\r\n"));
}
}while(bytesRead != 0);

Console.WriteLine("Connection to server lost.");
Console.ReadLine();
}
}
}