I'm trying to receive a broadcast via DatagramSockets in WinRT/C#, but I just don't receive a packet.
To be more specific, this is my code:
public sealed partial class MainPage : Page
{
public MainPage(){
this.InitializeComponent();
}
private DatagramSocket listener;
async private void Loaded(object sender, RoutedEventArgs e) {
listener = new DatagramSocket();
listener.MessageReceived += MessageReceived;
await listener.BindServiceNameAsync("50011");
}
private void MessageReceived(DatagramSocket sender, DatagramSocketMessageReceivedEventArgs args) {
txtText.Text = "Win :D:D:D:D:D:D:D"; //Breakpoint here
}
}
The program never reaches the breakpoint.
I've set all the correct rights/permissions in the appxmanifest.
The program which sends the broadcast is the following one:
static void Main(string[] args) {
Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
sock.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);
IPEndPoint iep = new IPEndPoint(IPAddress.Broadcast, 50011);
string hostname = Dns.GetHostName();
byte[] data = new byte[1];
data[0] = 129;
while (true) {
sock.SendTo(data, iep);
Console.WriteLine("Daten gesendet: {0}", data[0]);
Thread.Sleep(1000);
}
}
I know this program works, because I tested it with another little C# programm on the same PC (but not with WinRT functionality, just normal C#). Also it can't be a Firewall- or Routing Problem, because it, as I just mentioned, already worked with a normal C# program (but I already tried turning the firewall off).
I'm currently trying it on a Wifi-Network using Windows 8.1 and have x64 Processor.
Am I missing something? Is it even possible?
I hope somebody of you can help me
(PS: I know it's pretty similar to this post: Can't Receive UDP Windows RT but there hasen't been progress for more than a year so ...)
I solved it.
You just have to send the broadcasts from a different device.
However it doesn't like broadcasts sent from the same device ....
Related
I need to send a UDP broadcast from a RaspberryPi 3 running Windows 10 IoT Core. My code so far:
internal class UdpInterface : IDisposable
{
private UdpClient udpClient;
internal UdpInterface(int localPort)
{
udpClient = new UdpClient(localPort);
udpClient.EnableBroadcast = true;
}
internal void BroadcastMessage(string message, int targetPort)
{
IPEndPoint ip = new IPEndPoint(IPAddress.Broadcast, targetPort);
byte[] bytes = Encoding.ASCII.GetBytes(message);
udpClient.Send(bytes, bytes.Length, ip);
}
public void Dispose()
{
udpClient.Close();
udpClient.Dispose();
}
}
I call it like this from a GPIO pin ValueChanged event:
_udp.BroadcastMessage("Video" + PinMapper(sender.PinNumber), _port);
I tried setting the Internet (Client & Server) capability in package.appxmanifest, and I tried using the DatagramSocket class before.
Do I need some other permissions/capabilities or is something wrong with my code? It did work when sending to target IPs before.
I'm verifying the packet with PacketSender on my dev machine.
I'm now trying to connect STM32F429 to C# desktop application with ESP8266(in STA mode). I want ESP8266 to be a client and C# to be a Server. However ESP8266 remains failing to find my PC in the same LAN.
Now I have succeeded to use AT command to connect ESP8266 to my Router AP. And I used XAMPP to open a gate on my PC whose address is 192.168.1.11:80, then use the following command (AT+CIPSTART=\"TCP\",\"192.168.1.11\",80") to successfully connect ESP8266 to it(It returned OK to my STM32F429).
Then I wanna replace XAMPP with my C# code to open a TCP server. But I couldn't make it!
As for the C# Code, I have successfully build a connection between two C# programs (The IP Address is 192.168.1.11:80 which is the same as the one mentioned above).But when I tried to use ESP8266 to connect to the same IP and Port, it failed.
I suspected that there might be some wrong conceptions I have got about opening a TCP Listener on certain port in my LAN... I don't know...
The following is my C# code. (The code of STM32 is just a basic Usart code which I won't present here.)
// Code for Server
namespace Tcp_Server
{
public partial class Form1 : Form
{
private TcpListener myListener;
private TcpClient newClient;
public BinaryReader br;
public BinaryWriter bw;
public Form1()
{
InitializeComponent();
Thread myThread = new Thread(ServerA);
myThread.Start();
}
private void ServerA()
{
IPAddress SvrIP = new IPAddress(Dns.GetHostByName(Dns.GetHostName()).AddressList[0].Address); // Get the virtual IP of my PC.
this.Invoke(new AddToTextbox_dg(AddToTextbox), new object[] { tb_ServerStatus, ip.ToString() });
myListener = new TcpListener(ip, 80); //construct a Tcp Listener.
myListener.Start(); //Tcp Listener start
newClient = myListener.AcceptTcpClient();// Searching for a client...
this.Invoke(new AddToTextbox_dg(AddToTextbox), new object[] { tb_ServerStatus, "Connect Successfully" });
while (true)
{
try
{
NetworkStream clientStream = newClient.GetStream();
br = new BinaryReader(clientStream);
string receive = null;
receive = br.ReadString();//读取
this.Invoke(new AddToTextbox_dg(AddToTextbox), new object[] { tb_ServerStatus, receive });
}
catch
{
MessageBox.Show("Receving failed...");
}
}
}
// Code for client
namespace Client
{
public partial class Form1 : Form
{
private TcpClient client;
public BinaryReader br;
public BinaryWriter bw;
public Form1()
{
InitializeComponent();
Thread myThread = new Thread(ClientA);
myThread.Start();
}
private void ClientA()
{
IPAddress ip = new IPAddress(Dns.GetHostByName(Dns.GetHostName()).AddressList[0].Address); // Get the virtual IP of my PC.
client = new TcpClient(ip.ToString(), 80);
this.Invoke(new AddToTextbox_dg(AddToTextbox), new object[] { tb_ServerStatus, "Connect to Server Successfully!" });
while (true)
{
try
{
NetworkStream clientStream = client.GetStream();
br = new BinaryReader(clientStream);
string receive = null;
receive = br.ReadString();
}
catch
{
MessageBox.Show("Receving failed...");
}
}
}
private void AddToTextbox(TextBox txt, String s)
{
txt.Text += s;
}
private delegate void AddToTextbox_dg(TextBox txt, String s);
private void btn_send_Click(object sender, EventArgs e)
{
NetworkStream clientStream = client.GetStream();
bw = new BinaryWriter(clientStream);
bw.Write(message.Text);
}
}
}
Could somebody please help me with this problem ?
I wonder why I cannot connect ESP8266 to the TcpListener I built on my PC with C#.
What did my PC do when receiving the command:
myListener = new TcpListener(ip, 80);
This project I'm doing is about to transmit the image data I got with Stm32F429 and OV7725 to my PC through ESP8266. I know Usart will be too slow to do that, but now I'm just trying to build the connection. Is there any suggestion you guys could give me about this?
First, make sure no other application on your pc is listening to port 80. if so, you have to change it.
Second, try setting the ip of the TCPListener to local host "127.0.0.1". you will be able to reach this server by connecting to the ip of your PC.
I have checked the used IP in command window as below:
Command Window for checking IP usage
And I remain the IP address which ESP8266 will try to access to be 192.168.1.11:1900 which is the virtual IP of my PC in the LAN as below:
Address ESP8266 try to access
And change the IP C# will try to create a TCPListener on:
C# code
Is this what you mean? Thank you.
I have no trouble using a UDPClient's BeginReceive method from a console application. However, I am not able to get this to run from my WPF app. I'm very confused. I am assuming that it has something to do with where I am calling this code from. I am new to WPF. Is there something I'm misunderstanding about UDPClient's binding in WPF?
Does Inheriting from Application so something that could interfere with UDPClient BeginReceive()
Now this code call stack goes from App.xaml.cs, to ButtonClick(), that creates an instance of MachineItem and calls StartMachine. No weird threading or anything going on (unless WPF does something I'm not aware of during a button click). Again, BeginReceive() is called, but if I put a breakpoint in Receive(IAsyncResult res), nothing ever happens.
public partial class App : Application
{
//... all the normal stuff here
private void Button_Click(object sender, RoutedEventArgs e)
{
MachineItem currentMachine = (MachineItem)(sender as Button).DataContext;
currentMachine.StartMachine();
}
}
Now after button click, this happens:
public class MachineItem : INotifyPropertyChanged
{
IPEndPoint sendersEndPoint;
UdpClient listener;
public void StartMachine()
{
listener = new UdpClient
{
ExclusiveAddressUse = false
};
listener.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
IPAddress ip = System.Net.IPAddress.Parse(this.LocalNIC_IPAddress);
int ipInt = BitConverter.ToInt32(ip.GetAddressBytes(), 0);
IPEndPoint endPoint = new IPEndPoint(ipInt, 60811); //new IPEndPoint(IPAddress.Any, listenPort); this might allow me not to know the IP of this local device!
listener.Client.Bind(endPoint);
listener.BeginReceive(new AsyncCallback(Receive), null);
Thread.Sleep(20000); // this is just for testing purposes
}
private void Receive(IAsyncResult res)
{
byte[] bytes = listener.EndReceive(res, ref sendersEndPoint);
listener.BeginReceive(new AsyncCallback(Receive), null);
Console.WriteLine("Received");
}
}
Update:
I tried putting this UDP code where the application first starts to further narrow down the problem. I'm still getting the exact same behavior- the Client is able to call BeginReceive(), but then nothing happens even when UDP packets come in, in other words, the async method Receive() is never called...
public partial class WVGUIApp : Application
{
IPEndPoint sendersEndPoint;
UdpClient listener;
void AppStartup(object sender, StartupEventArgs args)
{
LoadMachineData();
MainWindow mainWindow = new MainWindow();
mainWindow.Show();
listener = new UdpClient
{
ExclusiveAddressUse = false
};
listener.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
IPAddress ip = System.Net.IPAddress.Parse("10.178.100.111");
int ipInt = BitConverter.ToInt32(ip.GetAddressBytes(), 0);
IPEndPoint endPoint = new IPEndPoint(ipInt, 60811); //new IPEndPoint(IPAddress.Any, listenPort); this might allow me not to know the IP of this local device!
listener.Client.Bind(endPoint);
listener.BeginReceive(new AsyncCallback(Receive), null);
//Thread.Sleep(20000);
}
private void Receive(IAsyncResult res)
{
byte[] bytes = listener.EndReceive(res, ref sendersEndPoint);
listener.BeginReceive(new AsyncCallback(Receive), null);
Console.WriteLine("Received");
}
}
I found the problem after many days of fighting this. The Windows Firewall was not allowing the debug build of the app through. This was hard for me to diagnose because because UDPClient.Send() was allowed, but UDPClient.BeginReceive() was not allowed through the firewall. This is easily fixed on windows 10 by going to Control Panel\All Control Panel Items\Windows Defender Firewall\Allowed apps\ and clicking the name of the app. Release version was allowed through, but debug has a different entry than release. Thank you MM8 for the help with sanity checks.
I'm writing a simple TCP-Connection software.
Firstly, I wrote the server in a ConsoleApp and it workes quite well.
Now I wanted to port it to a form application, but when a client connects, it does not add a new entry in my ListBox, on the Console it workes well.
I tried to write in the Load function as well as writing it in a separate Thread.
Both don't work.
In the Console it worked like this, and the Console wrote "User connected":
static void Main(string[] args)
{
const int PORT = 14758;
TcpListener server = new TcpListener(IPAddress.Any, PORT);
try
{
server.Start();
Console.WriteLine("Server started");
} catch (Exception Ex)
{
Console.WriteLine("Error", Ex);
}
TcpClient client = server.AcceptTcpClient();
Console.WriteLine("User connected");
Now in my form App it does not work like this:
public frmMainServer()
{
InitializeComponent();
Thread serverStart = new Thread(new ThreadStart(start_Server));
serverStart.Start();
serverStart.Join();
TcpClient client = server.AcceptTcpClient();
addItem("User connected");
}
As said before, I tried to write the last 2 lines in the Thread, too, but it didn't help.
I actually think I CAN connect to the server, so why does it not add the line?
addItem function:
private void addItem(string item)
{
_items.Add(item);
listStatus.DataSource = _items;
}
I am trying to create a multi-threading application that'll try and send a lot of data to a specific IP and port using sockets in C#. I have completed this, but I need help in getting more information from it.
I would like to know how I could get how much data is being sent a second? In MB if possible, from all threads and all requests?
I am mearly doing this for educational purposes to see how much data can actually be sent and how it all works when doing it with multi -threading
Here is my code:
static void Main(string[] args)
{
int amountOfThreads = 10;
while (amountOfThreads > 0)
{
Thread thread = new Thread(SendData);
thread.Start();
}
}
private static void SendData()
{
byte[] dataToSend = Encoding.Default.GetBytes("some string that'll be sent many times.");
string ipAddress = "127.0.0.1";
int port = 3924;
IPEndPoint ep = new IPEndPoint(IPAddress.Parse(ipAddress), port);
Socket socketToSendTo = new Socket(System.Net.Sockets.AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
socketToSendTo.SendTo(dataToSend, ep);
}