We are trying to build an UWP app with native messaging where the user will print labels on their network printers. Here is the code
string printerIPAddress = msg.ipAddress;
int printerPort = msg.port;
IPAddress addr = IPAddress.Parse(printerIPAddress);
IPEndPoint remoteEP = new IPEndPoint(addr, printerPort);
Socket clientSock =
new Socket(AddressFamily.InterNetwork,SocketType.Stream, ProtocolType.Tcp);
byte[] zplBytes = Encoding.ASCII.GetBytes((string)msg.zplText);
clientSock.Connect(remoteEP);
var bytesSent = clientSock.Send(zplBytes, zplBytes.Length, 0);
I am getting the following error:
Exception thrown:
'System.Net.Internals.SocketExceptionFactory.ExtendedSocketException'
in System.Net.Sockets.dll
System.Net.Internals.SocketExceptionFactory+ExtendedSocketException:
An attempt was made to access a socket in a way forbidden by its access permissions
We have built similar native messaging app for chrome and FF and we can print using network printer without any issue.
Related
I'm trying to build a load test application for a Grpc server. I would like the channels to open different ports whenever trying to connect to the server with disabling "SoResuePort Channel Option". By using the following code:
string Host = "192.168.1.20";
int Port = 7081;
IEnumerable<ChannelOption> options = new[] { new ChannelOption(ChannelOptions.SoReuseport, 0) };
ChannelOne = new Channel(Host, Port, ChannelCredentials.Insecure , options);
ChannelTwo = new Channel(Host, Port, ChannelCredentials.Insecure , options);
await ChannelOne.ConnectAsync();
await ChannelTwo.ConnectAsync();
I expect gRPC to open a new TCP connection per channel, but it's reusing the same TCP connection.
I have this code which works fine for project type of Console App (.NET Core).
class Program
{
static void Main(string[] args)
{
var L = new TcpListener(IPAddress.Any, 4994);
L.Start();
using (var C = L.AcceptTcpClientAsync().Result)
{
var S = C.GetStream();
var BR = new BinaryReader(S);
var BW = new BinaryWriter(S);
BW.Write("This is from Console!!!");
Console.WriteLine(BR.ReadString());
}
}
}
But when I use this code in project type of Blank App (Universal Windows) like this:
public MainPage()
{
InitializeComponent();
ThreadPool.RunAsync(foo);
}
static void foo(IAsyncAction operation)
{
var L = new TcpListener(IPAddress.Any, 4994);
L.Start();
using (var C = L.AcceptTcpClientAsync().Result)
{
var S = C.GetStream();
var BR = new BinaryReader(S);
var BW = new BinaryWriter(S);
BW.Write("This is from UWP!!!");
Debug.Write(BR.ReadString());
}
}
It will listen to that port when I check it by netstat but when the client wants to connect this exception will be thrown.
System.Net.Sockets.SocketException: 'A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond'
The UWP App has Private Networks (Client & Server) and Internet (Client & Server) capabilities.
Turning firewall on and off didn't help.
Target Version: Windows 10 Creators Update (10.0; Build 15063)
Client Code which is a WPF application:
using (var C = new TcpClient("127.0.0.1", 4994))
{
var S = C.GetStream();
var BR = new BinaryReader(S);
var BW = new BinaryWriter(S);
BW.Write("This is a test");
MessageBox.Show(BR.ReadString());
}
Debugging UWP & TCP listeners from localhost has always been problematic. Your code is OK and it should work if you try to connect into it from an external computer. The issue you're seeing is quite likely a bug/hyper-v issue/networking problem in the network isolation.
You can check if the network isolation for your app is enabled (it is by default) running the following from command prompt:
CheckNetIsolation.exe LoopbackExempt -s
My recommendation is to use an external computer to make sure that your code is fine (it should be). After that you can try to fight with the network isolation but that can be frustrating.
Here's an another issue where this has been discussed: Unable to access TCP Server inside a Windows Universal Application
I'm familiar with C#, and know some python. Recent days I'm learning the book Programming Python, 4th Edition and have run the very basic socket samples: echo-server.py and echo-client.py
They work well on my Windows, python 3.x.
python server:
from socket import *
myHost = 'localhost'
myPort = 50007
sockobj = socket(AF_INET, SOCK_STREAM)
sockobj.bind((myHost, myPort))
sockobj.listen(5)
while True:
connection, address = sockobj.accept()
print('Server connected by', address)
while True:
data = connection.recv(1024)
if not data: break
connection.send(b'Echo=>' + data)
connection.close()
Now I want to learn socket in C# too, so I wrote a C# .net framework 4.5 socket client, expecting to receive and show what echo-client.py does.
I got the C# demo from msdn and made some refactor to reduce code size.
public static void Main(string[] args)
{
string server = "localhost";
int port = 50007;
string request = "GET / HTTP/1.1\r\nHost: " + server +
"\r\nConnection: Close\r\n\r\n";
Byte[] sent = Encoding.ASCII.GetBytes(request);
Byte[] recv = new Byte[256];
IPHostEntry hostEntry = Dns.GetHostEntry(server);
IPEndPoint ipe = new IPEndPoint(hostEntry.AddressList[1], port);
Socket s =
new Socket(ipe.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
s.Connect(ipe);
s.Send(sent, sent.Length, 0);
int bytes = 0;
string page = "recived:\r\n";
//do
{
bytes = s.Receive(recv, recv.Length, 0);
page = page + Encoding.ASCII.GetString(recv, 0, bytes);
}
//while (bytes > 0);
Console.WriteLine(page);
Console.WriteLine("result");
Console.ReadKey();
}
My test steps:
If I set up a web site using local IIS, such as
http://localhost:801, then above code can show the homepage html
contents, this means my C# code is working.
Run echo-server.py, and change C# code's port to 50007, then run,
nothing output in console, and application does not exit, if I place a break point within the loop, I can see the loop has only run once. The python server did output some log saying C# is connecting.
Comment do while loop(as commented in code), this time the output is exactly same as echo-client.py(expected).
So I'm wondering what's wrong when I'm using do while loop?
I'm trying to establish a connection with a custom bluetooth device without using COM ports. However, I'm getting an error: [10049] "The requested address is not valid in its context". What am I doing wrong?
static Guid serviceClass= new Guid("4d36e978-e325-11ce-bfc1-08002be10318"); //GUID of device class
static BluetoothAddress addr = BluetoothAddress.Parse("001210160177"); //from device
BluetoothDeviceInfo device = new BluetoothDeviceInfo(addr);
device.SetServiceState(serviceClass, true);
Console.WriteLine(BluetoothSecurity.PairRequest(device.DeviceAddress, "0000")); //pairing my device - writes True
BluetoothEndPoint ep = new BluetoothEndPoint(addr, serviceClass);
BluetoothClient conn = new BluetoothClient(ep); //10049 error
conn.Connect(ep);
Console.WriteLine(conn.GetStream());
Its all covered in the project's documentation. :-)
In short, remove that SetServiceState line it is unnecessary/bad. Doing the pairing each time is also unnecessary and a bit slow but probably not worth changing if its working well.
Docs:
1) http://32feet.codeplex.com/documentation
"See section General Bluetooth Data Connections below. The BluetoothClient provides the Stream to read and write on -- there is no need to use virtual COM ports"
2) http://32feet.codeplex.com/wikipage?title=General%20Bluetooth%20Data%20Connections
BluetoothAddress addr
= BluetoothAddress.Parse("001122334455");
Guid serviceClass;
serviceClass = BluetoothService.SerialPort;
// - or - etc
// serviceClass = MyConsts.MyServiceUuid
//
var ep = new BluetoothEndPoint(addr, serviceClass);
var cli = new BluetoothClient();
cli.Connect(ep);
Stream peerStream = cli.GetStream();
peerStream.Write/Read ...
3) http://32feet.codeplex.com/wikipage?title=Errors
10049 "The requested address is not valid in its context."
No Service with given Service Class Id is running on the remote device
i.e. Wrong Service Class Id.
Here's how it finally rolls.
device.SetServiceState(serviceClass, true); //do it before pairing
...
BluetoothClient conn = new BluetoothClient();
conn.Connect(ep);
Also, my mistake here:
static Guid serviceClass = new Guid("4d36e978-e325-11ce-bfc1-08002be10318");
//GUID of device class
Should be:
static Guid serviceClass = new Guid("00001101-0000-1000-8000-00805f9b34fb");
//GUID of bluetooth service
For seeing the proper GUID, refer to your device's (not dongle's) settings/properties. You can see them from Windows.
i have done a server using this example socketAsyncEventArgs
in visual studio 2010 and .net 4.0.
Now i'm trying to connect to it from a windows 8 app using StreamSocket but i'm getting a "Acces denied" message.
here is the Client code:
private StreamSocket streamSocket;
public string Server = "192.168.0.101";
public int Port = 9900;
public async void Connect()
{
streamSocket = new StreamSocket();
Connect();
try
{
await streamSocket.ConnectAsync(
new Windows.Networking.HostName(Server),
Port.ToString()); // getting Acces Denied here
DataReader reader = new DataReader(streamSocket.InputStream);
reader.InputStreamOptions = InputStreamOptions.Partial;
while (true)
{
var bytesAvailable = await reader.LoadAsync(1000);
var byteArray = new byte[bytesAvailable];
reader.ReadBytes(byteArray);
}
}
catch (Exception e)
{
MessageBox(e.StackTrace);
}
}
How to fix the problem? Is there another way to send and receive messages using this server?
You are probably also seeing the following as part of your error message:
WinRT information: A network capability is required to access this network resource
This is because you need to add a capability to your application that allows you to access local networks. Double click on the Package.appxmanifest file in your project. Click on the Capabilities tab. Add the Private Networks (Client & Server) capability to your project.