What I am wanting to do is create a SocketStreamListener and connect to it (on localhost). Then connect to it and send it a message. Very simple stuff and it’s all done here in an official demo but I want to understand it and use this logic in my own application.
The Problem
I have created a new Windows Metro C# application project and have this code to create a listener on my MainPage:
private void Button_Click(object sender, RoutedEventArgs e)
{
StreamSocketListener listener = new StreamSocketListener();
greetingOutput.Text = "Hello, " + nameInput.Text + "!";
}
but I get this error:
An exception of type ‘System.UnauthorizedAccessException’ occurred in
HelloWorld.exe but was not handled in user codeWinRT information: At least one of either InternetClientServer or
PrivateNetworkClientServer capabilities is required to listen for or
receive trafficAdditional information: Access is denied.
If there is a handler for this exception, the program may be safely
continued.
The same code works in the official demo though.
What am I missing?
What am I doing wrong?
You need to configure your application to require one or both of the necessary capabilities depending on your needs:
internetClientServer
privateNetworkClientServer
(From the documentation at http://msdn.microsoft.com/en-us/library/windows/apps/br211423.aspx)
Also see this article for more information on how capabilities works: http://msdn.microsoft.com/en-us/library/windows/apps/hh464936.aspx
You need to declare which capabilities your app requires (and therefore has access to)
in your package manifest. Here’s a step by step guide on how to do that: http://msdn.microsoft.com/en-us/library/windows/apps/br211477.aspx
You can use the Manifest Designer in Visual Studio to edit these capabilities.
Just locate and open the file in your solution named
package.appxmanifestand the Manifest Designer should open.Select the capabilities tab and the network related capabilities your app requires and you should be good to go.
Link to the documentation about the App Manifest Designer: http://msdn.microsoft.com/en-us/library/windows/apps/br230259(v=vs.110).aspx
Regarding the last paragraph
It is simply saying that you may wrap your code using the
StreamSocketListenerin a try-catch block. This is a good thing if you want to handle the missing capabilities gracefully inside your application: