Reputation: 23
I'm trying to create a windows application with Visual Studio 2012 but weird stuff seems to be happening... When I run the exact same code in a console app, it works fine but it seems that I can't output the following once I run it in a thread on a windows application project:
private void VisualUDPListener_Load(object sender, EventArgs e)
{
//System.Windows.Forms.Form.CheckForIllegalCrossThreadCalls = false;
new Thread(delegate()
{
StartListener();
}).Start();
}
private void StartListener()
{
UdpClient listener = new UdpClient(listenPort);
IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, listenPort);
try
{
while (true)
{
//log text box
Log.AppendText("Listening \n");
byte[] bytes = listener.Receive(ref groupEP);
string hex_string = BitConverter.ToString(bytes);//this works and returns the correct hex data
string ascii_string = Encoding.ASCII.GetString(bytes, 0, bytes.Length);//blank???????????
MessageBox.Show(ascii_string.Length.toString());//outputs 131 which is correct
MessageBox.Show(ascii_string);// shows a blank message box
Log.AppendText("--" + ascii_string + hex_string +" \n");//only outputs --
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
finally
{
listener.Close();
}
}
I target .NET Framework 4.5... If I send UDP data from a test java app it receives the data fine but if I send the exact same data through a mobile device which the code is intended for it comes out empty like in the comments above. (Then the device must be sending corrupt data? nope because if the code above is run in a console app it runs perfectly and outputs the correct strings)
Any help would be greatly appreciated.
Upvotes: 2
Views: 2026
Reputation: 3834
As noted in comments, the string starts with 0 byte (00-04-02-00-20).
This correctly gets converted to C# string. MessageBox.Show
invokes windows api function MessageBox
. Windows API uses zero-terminated strings, so this specific string appears empty to WinAPI, because first byte is zero. You cannot log/display this string verbatim with APIs that use zero-terminated strings.
You need either to replace 0s with something else, like ascii_string.Replace((char)0, (char)1)
or use apis which don't treat zeros as special characters.
Upvotes: 3