这是我连接到 Asterisk Manager 界面的代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text.RegularExpressions;
using System.Text;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Net;
using System.IO;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
private Socket clientSocket;
private byte[] data = new byte[1024];
private int size = 1024;
//------------------------------------------------------------------------------------------
public Form1()
{
InitializeComponent();
}
//------------------------------------------------------------------------------------------
[STAThread]
private void BtnConnect_Click(object sender, EventArgs e)
{
try
{
AddItem("Connecting...");
clientSocket = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
IPEndPoint iep = new IPEndPoint(IPAddress.Parse("192.168.1.155"), 5038);
clientSocket.BeginConnect(iep, new AsyncCallback(Connected), clientSocket);
}
catch (Exception exp)
{
AddItem(exp.Message);
}
}
//------------------------------------------------------------------------------------------
private void BtnDisconnect_Click(object sender, EventArgs e)
{
clientSocket.Close();
}
//------------------------------------------------------------------------------------------
void Connected(IAsyncResult iar)
{
clientSocket = (Socket)iar.AsyncState;
try
{
clientSocket.EndConnect(iar);
AddItem("Connected to: " + clientSocket.RemoteEndPoint.ToString());
clientSocket.BeginReceive(data, 0, size, SocketFlags.None,
new AsyncCallback(OnDataReceive), clientSocket);
}
catch (Exception exp)
{
AddItem("Error connecting: " + exp.Message);
}
}
//------------------------------------------------------------------------------------------
private void OnDataReceive(IAsyncResult result)
{
Socket remote = (Socket)result.AsyncState;
int recv = remote.EndReceive(result);
string stringData = Encoding.ASCII.GetString(data, 0, recv);
AddItem(stringData);
}
//------------------------------------------------------------------------------------------
private delegate void stringDelegate(string s);
private void AddItem(string s)
{
if (ListBoxEvents.InvokeRequired)
{
stringDelegate sd = new stringDelegate(AddItem);
this.Invoke(sd, new object[] { s });
}
else
{
ListBoxEvents.Items.Add(s);
}
}
//------------------------------------------------------------------------------------------
private void BtnLogin_Click(object sender, EventArgs e)
{
clientSocket.Send(Encoding.ASCII.GetBytes("Action: Login\r\nUsername: admin\r\nSecret: lastsecret\r\nActionID: 1\r\n\r\n"));
}
//------------------------------------------------------------------------------------------
}
}
问题是当我连接到服务器时,我收到“Asterisk Call Manager/1.1”消息。连接到服务器后,我登录到服务器,但没有收到任何消息。我想从星号获取事件。使用网络Socket有问题吗?我是否应该使用特殊命令告诉星号我想接收事件。