capture data from Panasonic PBX using c# - c#

I have written the below code to capture data from Panasonic PBX(KX-TDE 100/200) and write it to a file.
When I try to run the below code, it shows "not responding" in the Task Manager.
Also I tried to debug where might be the problem.The line
Socket socket = listener.Accept(); will be hit while debugging and after that it shows "Not Responding".
The PBX is connected to LAN in my company.Any configurations need to be done on my LAN?
I tried the same code for IP:127.0.0.1 to send a string to client app and it worked.But when I tried to pull data from PBX, its not working.
The LAN wire from my PBX is connected to the switch.
Please let me know what mistake I am doing. Also point me to good samples on capturing data from PBX using C#.
private void btnstartserver_Click(object sender, EventArgs e)
{
int portno = Convert.ToInt32(txtportnum.Text);
byte[] receivedBytes = new byte[1024];
IPHostEntry ipHost = Dns.GetHostEntry(Dns.GetHostName());
IPAddress ipAddress = ipHost.AddressList[0];
IPEndPoint ipEndPoint = new IPEndPoint(ipAddress, portno);//2112
txtboxstatus.Text = "Creating socket object...";
Socket listener = new Socket(AddressFamily.InterNetworkV6,
SocketType.Stream,
ProtocolType.Tcp);
listener.Bind(ipEndPoint);
listener.Listen(10);
txtboxstatus.AppendText("Listening on " + ipHost.AddressList[0].ToString() + ":" + portno.ToString() + "\r\n");
Socket socket = listener.Accept();
txtboxstatus.AppendText ( "\n Connected with ..." + ipEndPoint.Port);
string receivedvalue = string.Empty;
receivedvalue = ReadMessage(socket);
txtboxstatus.AppendText("\n Message read.....trying to write to the file...");
//writing the received value from client into a file.
try
{
FileStream fs = new FileStream("E:/Demo/IpData/Call.txt", FileMode.Create);
StreamWriter sw = new StreamWriter(fs);
sw.Write(receivedvalue);
sw.Dispose();
fs.Dispose();
}
catch (Exception ex)
{
txtclient.AppendText(ex.Message);
}
}
Update to this question.
I have written a new code to connect to PBX.With the new code I was able to connect to the PBX.Please find below.
private void btnTx_Click(object sender, EventArgs e)
{
byte[] receivedBytes = new byte[1024];
int portno = Convert.ToInt32(txtportnum.Text);
IPHostEntry ipHost = Dns.GetHostByName("192.168.x.yyy");
IPAddress ipAddress = ipHost.AddressList[0];
IPEndPoint ipEndPoint = new IPEndPoint(ipAddress, portno);
txtstatus.Text = "Creating socket object...";
Socket send_soc = new Socket(AddressFamily.InterNetwork,
SocketType.Stream,
ProtocolType.Tcp);
send_soc.Connect(ipEndPoint);
txtstatus.AppendText("\nSuccessfully connected to:" + "\t" + send_soc.RemoteEndPoint);
txtstatus.AppendText("\nConnecting via :" + "\t" + send_soc.LocalEndPoint);
string sendingMessage = "abcde";
SendMessage(send_soc, sendingMessage);
int totalBytesReceived = send_soc.Receive(receivedBytes);
string dff = "";
string s = System.Text.ASCIIEncoding.ASCII.GetString(receivedBytes, 0, totalBytesReceived);
txtRx.AppendText(s);
send_soc.Shutdown(SocketShutdown.Both);
send_soc.Close();
try
{
FileStream dr = new FileStream("E:/Demo/IpData/Call.txt", FileMode.OpenOrCreate, FileAccess.Read, FileShare.ReadWrite);
StreamReader fg = new StreamReader(dr);
string df = fg.ReadToEnd();
dff = df;
fg.Dispose();
dr.Dispose();
}
catch (Exception dfjdfs)
{
throw dfjdfs;
}
try
{
File.Delete("E:/Demo/IpData/Call.txt");
}
catch (Exception jhu)
{
throw jhu;
}
try
{
FileStream cd = new FileStream("E:/Demo/IpData/Call.txt", FileMode.Create);
StreamWriter cdf = new StreamWriter(cd);
cdf.Write(dff);
cdf.Write(s);
cdf.Dispose();
cd.Dispose();
}
catch (Exception hgy)
{
throw hgy;
}
}
static void SendMessage(Socket socket, string msg)
{
byte[] data = System.Text.ASCIIEncoding.ASCII.GetBytes(msg);
socket.Send(data);
}
But I am not able to receive any data from PBX except "-" plus whatever I send in "sendingMessage" variable.For example if sendingMessage="abcde",I will receive -abcde
Also the documentation is describing how to configure PBX box.Also for the PBX to return the data, we need to send valid credentials. How to send this valid credentials?

You should type "SMDR" and enter after "-" for going to smdr mode, then type "PCCSMDR" as password and enter for public Panasonic models.

Don't make blocking calls, (like accept), in a GUI event-handler.
Thread off the server or use asynch.

Related

How I can to create python(or swift) TCP client for my TCP c# server?

How I can to create python(or swift) TCP client for my TCP c# server?
c# API for my TCP server:
Client client = Client();
bool Connect()
{
UserInfo userInfo = new UserInfo("login", "pass");
NetworkConnectionParam connectionParams = new NetworkConnectionParam("127.0.0.1", 4021);
try
{
client.Connect(connectionParams,userInfo,ClientInitFlags.Empty);
}
catch
{
return false;
}
return client.IsStarted;
}
I try it(python) :
import socket
sock = socket.socket()
sock.connect(('localhost', 4021))
But I don't uderstand how I must to send my login and password (like in API for c#).
I don`t undestand what you want to implement.
If you want to run Python code in C#, then look at this IronPython
If you want to implement TCP client in C#, then try smth like this:
using System.Net;
using System.Net.Sockets;
class Program
{
static int port = 8005; // your port
static void Main(string[] args)
{
// get address to run socket
var ipPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), port);
// create socket
var listenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
// binding
listenSocket.Bind(ipPoint);
// start listen
listenSocket.Listen(10);
Console.WriteLine("Server is working");
while (true)
{
Socket handler = listenSocket.Accept();
// recieve message
StringBuilder builder = new StringBuilder();
int bytes = 0; // quantity of received bytes
byte[] data = new byte[256]; // data buffer
do
{
bytes = handler.Receive(data);
builder.Append(Encoding.Unicode.GetString(data, 0, bytes));
}
while (handler.Available>0);
Console.WriteLine(DateTime.Now.ToShortTimeString() + ": " + builder.ToString());
// send response
string message = "your message recieved";
data = Encoding.Unicode.GetBytes(message);
handler.Send(data);
// close socket
handler.Shutdown(SocketShutdown.Both);
handler.Close();
}
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}

Error "Only one usage of each socket address (protocol/network address/port) is normally permitted"

I am working on sender and receiver in windows application using socket/tcplistener.
I am getting this error
Only one usage of each socket address (protocol/network address/port)
is normally permitted
Error is coming in catch block of StartReciever method
Below is my code.
// On button click
private void btnLoadFile_SendFile_Click(object sender, EventArgs e)
{
StartReciever();
SendData(tcpIpAddress, port, filename);
}
private void StartReciever()
{
util.LoadSettings();
string tcpIpAddress = util.svrSettings["IpAddress"];
string port = util.svrSettings["Port"];
string outDir = util.svrSettings["isOutput"];
new Thread(
() =>
{
if (!File.Exists(util.settingFile))
Logger("Please setup the services first.");
else
{
try
{
IPAddress ipAddress = IPAddress.Parse(tcpIpAddress);
TcpListener tcpListener = new TcpListener(ipAddress, Convert.ToInt32(port));
tcpListener.Start();
Logger("\nWaiting for a client to connect...");
//blocks until a client connects
Socket socketForClient = tcpListener.AcceptSocket();
Logger("\nClient connected");
//Read data sent from client
NetworkStream networkStream = new NetworkStream(socketForClient);
int bytesReceived, totalReceived = 0;
string fileName = "testing.txt";
byte[] receivedData = new byte[10000];
do
{
bytesReceived = networkStream.Read
(receivedData, 0, receivedData.Length);
totalReceived += bytesReceived;
Logger("Progress of bytes recieved: " + totalReceived.ToString());
if (!File.Exists(fileName))
{
using (File.Create(fileName)) { };
}
using (var stream = new FileStream(fileName, FileMode.Append))
{
stream.Write(receivedData, 0, bytesReceived);
}
}
while (bytesReceived != 0);
Logger("Total bytes read: " + totalReceived.ToString());
socketForClient.Close();
Logger("Client disconnected...");
tcpListener.Stop();
}
catch (Exception ex)
{
// Error : "Only one usage of each socket address (protocol/network address/port) is normally permitted"
Logger("There is some error: " + ex.Message);
}
}
}).Start();
}
private static void SendData(string tcpIpAddress, string port, string filename)
{
new Thread(
() =>
{
TcpClient tcpClient = new TcpClient(tcpIpAddress, Convert.ToInt32(port));
//const int bufsize = 8192;
const int bufsize = 10000;
var buffer = new byte[bufsize];
NetworkStream networkStream = tcpClient.GetStream();
using (var readFile = File.OpenRead(filename))
{
int actuallyRead;
while ((actuallyRead = readFile.Read(buffer, 0, bufsize)) > 0)
{
networkStream.Write(buffer, 0, actuallyRead);
}
}
}).Start();
}
My guess is that the receiver started by the first button click is still running, so when you try to set up a second TcpListener on the same address and port, you get the exception.
You should add some code that prevent you from creating two identical listeners in parallel.
You call StartReceiver method right in your Click event handler, that's why it tries to open the same port the second time. It only needs to be called once, move it elsewhere, say in your program initialization code.

C# client communication Via UPD

I am looking for some help with communication between my server application and my client.The idea is that my client will listen for a UDP packet, read it and then execute a command based on what it reads.
My issue is that the server sends the packet however the client does nothing.
Here is a snippet of my code:
Client:
public void listen()
{
try
{
MessageBox.Show("");
UdpClient receivingUdpClient = new UdpClient(11000);
IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 11000);
try
{
// Blocks until a message returns on this socket from a remote host.
Byte[] receiveBytes = receivingUdpClient.Receive(ref RemoteIpEndPoint);
string returnData = Encoding.ASCII.GetString(receiveBytes);
string[] split = returnData.Split(':');
if (split[0] == "SayHello")
{
MessageBox.show("Hello user","Hello");
}
//Note i have many commands but i shortened it to save room.
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
Server:
else if (radioButton4.Checked)
{
UdpClient udpClient = new UdpClient([IP_ADDRESS_HERE], 11000);
body = richTextBox1.Text;
title = textBox1.Text;
Command = "Message" + ":" + body + ":" + title + ":" + 4;
Byte[] sendBytes = Encoding.ASCII.GetBytes(Command);
try
{
udpClient.Send(sendBytes, sendBytes.Length);
}
catch (Exception)
{
Console.WriteLine(e.ToString());
}
}
Just wanted to see if you guys are able to find something I overlooked.
Check your Windows Firewall and verify it's not blocking your Client from opening port 11000.
Control Panel-> System and Security -> Windows Firewall

C# UdpClient.Receive() not working with multicast no matter what I do

tried to solve this alone for the past I don't even know but no googling will help me here, I would need some advice with this one. I am receiving UDP packets from another PC on my local network every 10 seconds, can see them in wireshark but the application is stuck on the udpClient.Receive() line. The multicast group and port are the right values, checked in main() n+1 times. Please suggest a solution if you have any idea that might help. Thanks.
(I'm trying to receive the server's information so that th application can automaticaly start to communicate vith it via TCP)
class MulticastListener {
private UdpClient udpClient;
private IPEndPoint remoteEndPoint;
IPAddress multicastIP;
private int port;
public MulticastListener(ref IPAddress multicastIP, int port) {
remoteEndPoint = new IPEndPoint(IPAddress.Any, port);
this.multicastIP = multicastIP;
this.port = port;
udpClient = new UdpClient();
udpClient.Client.Bind(remoteEndPoint);
}
public IPEndPoint GetServer() {
try {
udpClient.JoinMulticastGroup(multicastIP);
} catch (ObjectDisposedException e) {
Console.WriteLine("ERROR: The underlying socket has been closed!");
} catch (SocketException e) {
Console.WriteLine("ERROR: An error occurred when accessing the socket!");
} catch (ArgumentException e) {
Console.WriteLine("ERROR: The IP address is not compatible with the AddressFamily value that defines the addressing scheme of the socket!");
}
Byte[] serverInfoBytes = udpClient.Receive(ref remoteEndPoint);
Stream stream = new MemoryStream(serverInfoBytes); //receives a serialised IPEndpoint object
BinaryFormatter formatter = new BinaryFormatter();
udpClient.Close();
return (IPEndPoint)formatter.Deserialize(stream);
}
}
As I commented, your code works fine for me 100% as is. I would check you are sending on the same subnet you are receiving on. Perhaps your sender is not configured to the right interface?
Perhaps it would help to try out a different sender, here is what I used to test:
static void Main(string[] args)
{
//Configuration
var interfaceIp = IPAddress.Parse("192.168.9.121");
var interfaceEndPoint = new IPEndPoint(interfaceIp, 60001);
var multicastIp = IPAddress.Parse("230.230.230.230");
var multicastEndPoint = new IPEndPoint(multicastIp, 60001);
//initialize the socket
var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
socket.ExclusiveAddressUse = false;
socket.MulticastLoopback = false;
socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1);
MulticastOption option = new MulticastOption(multicastEndPoint.Address, interfaceIp);
socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, option);
//bind on a network interface
socket.Bind(interfaceEndPoint);
//initialize args for sending packet on the multicast channel
var sockArgs = new SocketAsyncEventArgs();
sockArgs.RemoteEndPoint = multicastEndPoint;
sockArgs.SetBuffer(new byte[1234], 0, 1234);
//send an empty packet of size 1234 every 3 seconds
while (true)
{
socket.SendToAsync(sockArgs);
Thread.Sleep(3000);
}
}

Socket connection in CF 3.5 C#

I am trying to establish a communication between a handheld and a PC.
I have the following code, for the client:
public void connect(string IPAddress, int port)
{
// Connect to a remote device.
try
{
IPAddress ipAddress = new IPAddress(new byte[] { 192, 168, 1, 10 });
IPEndPoint remoteEP = new IPEndPoint(ipAddress, port);
// Create a TCP/IP socket.
client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
// Connect to the remote endpoint.
client.BeginConnect(remoteEP, new AsyncCallback(ConnectCallback), client);
if (connectDone.WaitOne()){
//do something..
}
else{
MessageBox.Show("TIMEOUT on WaitOne");
}
}
catch(Exception e){
MessageBox.Show(e.Message);
}
}
My problem is that when I run both of them in a pc they communicate fine, but the same code in a SmartDevice Project doesn't connect with the Server which is running on the PC and it give me this error:
System.Net.Sockets.SocketException: A connection attempt failed because the connected party did not properly respond after a period of time, or stablished connection failed
because connected host has failed to respond
What am I missing?
NOTE: The IPAddress is hard coded inside the code
EDIT: here is another code which I take from a MSDN example. This don't work either, it says that it not possible to read. The server code in this case is the same as the example, the client code have a modification:
private void button1_Click(object sender, EventArgs e)
{
// In this code example, use a hard-coded
// IP address and message.
string serverIP = "192.168.1.10";//HERE IS THE DIFERENCE
string message = "Hello";
Connect(serverIP, message);
}
Thanks in advance for any help!
For my "mobile device" client, I send data to the "PC" host using this:
private void Send(string value) {
byte[] data = Encoding.ASCII.GetBytes(value);
try {
using (TcpClient client = new TcpClient(txtIPAddress.Text, 8000)) {
NetworkStream stream = client.GetStream();
stream.Write(data, 0, data.Length);
}
} catch (Exception err) {
// Log the error
}
}
For the host, you're best to use a thread or BackgroundWorker where you can let a TcpListener object sit and wait:
private void Worker_TcpListener(object sender, DoWorkEventArgs e) {
BackgroundWorker worker = (BackgroundWorker)sender;
do {
string eMsg = null;
int port = 8000;
try {
_listener = new TcpListener(IPAddress.Any, port);
_listener.Start();
TcpClient client = _listener.AcceptTcpClient(); // waits until data is avaiable
int MAX = client.ReceiveBufferSize;
NetworkStream stream = client.GetStream();
Byte[] buffer = new Byte[MAX];
int len = stream.Read(buffer, 0, MAX);
if (0 < len) {
string data = Encoding.UTF8.GetString(buffer);
worker.ReportProgress(len, data.Substring(0, len));
}
stream.Close();
client.Close();
} catch (Exception err) {
// Log your error
}
if (!String.IsNullOrEmpty(eMsg)) {
worker.ReportProgress(0, eMsg);
}
} while (!worker.CancellationPending);
}

Categories