C# client communication Via UPD - c#

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

Related

Reconnecting to an unclosed Socket connection C#

I have a Listener application which expects a string message for display. I cannot modify this application.
I have to send messages to this listener through my C# client. Both the listener and client are supposed to run on the same PC (local host).
My Code to Connect:
public void ConnectAndSendMessage(string MessageToSend)
{
string localIP = GetIPAddress();
try
{
TcpClient tcpclnt = new TcpClient();
Console.WriteLine("Connecting.....");
tcpclnt.Connect(localIP, 2400);
Socket socket = tcpclnt.Client;
bool connectionStatus = socket.Connected;
if (connectionStatus)
{
//Send Message
ASCIIEncoding asen = new ASCIIEncoding();
//string sDateTime = DateTime.Now.ToString();
int SendStatus = socket.Send(asen.GetBytes(MessageToSend + Environment.NewLine));
}
Thread.Sleep(2000);
tcpclnt.Close();
}
catch (Exception e)
{
Console.WriteLine("Error..... " + e.StackTrace);
}
}
Problem:
The client application runs fine and send the messages successfully to the Listener. But the problem comes if the client gets crashed (I close the client program) before executing tcpclnt.Close();. In this case, if I restart the Client program again then, I cannot connect to the socket since the application didn’t close the socket in the previous run (crashed run).
How can I reconnect to the listener in this condition?
try this one..
public void ConnectAndSendMessage(string MessageToSend)
{
string localIP = GetIPAddress();
using (System.Net.Sockets.TcpClient tcpclnt = new System.Net.Sockets.TcpClient())
{
try
{
Console.WriteLine("Connecting.....");
tcpclnt.Connect(localIP, 2400);
using (System.Net.Sockets.Socket socket = tcpclnt.Client)
{
if (socket.Connected)
{
//Send Message
System.Text.ASCIIEncoding asen = new System.Text.ASCIIEncoding();
//string sDateTime = DateTime.Now.ToString();
int SendStatus = socket.Send(asen.GetBytes(MessageToSend + Environment.NewLine));
}
System.Threading.Thread.Sleep(2000);
}
}
catch (Exception e)
{
Console.WriteLine("Error..... " + e.StackTrace);
}
finally
{
if (tcpclnt != null && tcpclnt.Connected)
tcpclnt.Close();
}
}
}

Server socket in Android, Client sockect C# not sending until socket close

I have a socket server in Android and a client Socket in C#. The socket stablish connection properly but the information is not sended until the socket is close. Ot seems that the information is in buffer and it is not sended until the resources must be released.
The server code is:
Socket socket = null;
DataInputStream dataInputStream = null;
DataOutputStream dataOutputStream = null;
try {
serverSocket = new ServerSocket(SocketServerPORT);
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
info.setText("I'm waiting here: "+ serverSocket.getLocalPort());
}
});
while (true) {
socket = serverSocket.accept();
dataInputStream = new DataInputStream(socket.getInputStream());
dataOutputStream = new DataOutputStream(socket.getOutputStream());
String messageFromClient = "";
//If no message sent from client, this code will block the program
messageFromClient = dataInputStream.readLine();
count++;
message += "#" + count + " from " + socket.getInetAddress()+ ":" + socket.getPort() + "\n" + "Msg from client: " + messageFromClient + "\n";
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
msg.setText(message);
}
});
And the client code is:
IPAddress host = IPAddress.Parse("192.168.1.129");
IPEndPoint hostep = new IPEndPoint(host, 8080);
Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
sock.Connect(hostep);
//sock.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.NoDelay, true);
}
catch (SocketException ex) {
Console.WriteLine("Problem connecting to host");
Console.WriteLine(e.ToString());
sock.Close();
return;
}
try
{
string theMessageToSend = "Que mierda es esta";
byte[] msg = Encoding.Unicode.GetBytes(theMessageToSend + "$");
sock.Send(msg);
//sock.Send(Encoding.ASCII.GetBytes("testing %"));
} catch (SocketException ex) {
Console.WriteLine("Problem sending data");
Console.WriteLine( e.ToString());
sock.Close();
return;
}
sock.Close();
I can not reach the line messageFromClient = dataInputStream.readLine(); in the server side until the sock.Close(); is executed in the client side.
Many thanks in advance!

Can I broadcast in a network but exclude myself?

I'm using C# to create a client-server network. I created client successfully but i have an issue with the server. When i broadcast a message to the server it's supposed to send it to other clients as well. The problem is that the server too gets the message then it thinks it's another message and it creates an infinite loop that sends the same message over and over again. Can I broadcast excluding the server?
public void serverThread()
{
while (true)
{
IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
Byte[] receiveBytes = udpClient_rec.Receive(ref RemoteIpEndPoint);
string returnData = Encoding.ASCII.GetString(receiveBytes);
if (returnData.StartsWith("broad"))
{
UdpClient udpClient_send = new UdpClient();
IPEndPoint RemoteIpEndPoint1 = new IPEndPoint(IPAddress.Broadcast, 8400);
//can i use something else here instead of broadcast to send it to everyone except myself(server)?
udpClient_send.EnableBroadcast = true;
udpClient_send.Send(receiveBytes, receiveBytes.Length, RemoteIpEndPoint1);
udpClient_send.Close();
}
this.SetText(RemoteIpEndPoint.Address.ToString() + ": " + returnData.ToString());
this.SetText2(RemoteIpEndPoint.Address.ToString());
}
}

capture data from Panasonic PBX using 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.

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