I'm trying to connect to a StreamSocketListener in my Windows 10 app. This is working if the client socket is inside the same app. But if I try to connect from another application (e.g. Putty) it doesn't work. After a few seconds putty says "Network Error: Connection Refused".
Here is my sample code:
public sealed partial class MainPage : Page
{
private StreamSocketListener listener;
public MainPage()
{
this.InitializeComponent();
listener = new StreamSocketListener();
listener.ConnectionReceived += Listener_ConnectionReceived;
listener.BindServiceNameAsync("12345").AsTask().Wait();
}
private async void Listener_ConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
{
Debug.WriteLine("new connection");
string message = "Hello World!";
using (var dw = new DataWriter(args.Socket.OutputStream))
{
dw.WriteString(message);
await dw.StoreAsync();
dw.DetachStream();
}
}
private async void Button_Click(object sender, RoutedEventArgs e)
{
// Test connection
var serverHost = new HostName("localhost");
var socket = new StreamSocket();
await socket.ConnectAsync(serverHost, "12345");
using (var dr = new DataReader(socket.InputStream))
{
dr.InputStreamOptions = InputStreamOptions.Partial;
await dr.LoadAsync(12);
var input = dr.ReadString(12);
Debug.WriteLine("received: " + input);
}
}
}
In XAML i added a button to test the client connection.
In the manifest i have checked "Internet (Client)", "Internet (Client & Server)" and "Private Networks (Client & Server)".
EDIT: I'm trying to connect on the same computer. Firewall is deactivated.
You cannot connect to a StreamSocketListener from another app or process running in the same computer, not even with a loopback exemption. You will need to run the client in a different machine.
You can connect to a localhost UWP server app only if you disable the windows firewall (via the control panel) before starting the app, and then quit the firewall service ("net stop MpsSvc", from elevated command prompt) after the app has been started. Loopbackexemption doesn't enable connections to UWP apps, only from UWP apps, in my experience at least...
regards
Related
I am using 32Feet.Net's sample (list below) with using statements removed for brevity.
static void Main(string[] args)
{
BluetoothClient client = new BluetoothClient();
BluetoothDeviceInfo device = null;
foreach (var dev in client.DiscoverDevices())
{
if (dev.DeviceName.Contains("moto g(6)"))
{
device = dev;
break;
}
}
client.Connect(device.DeviceAddress, BluetoothService.SerialPort);
client.Close();
}
The line client.Connect(device.DeviceAddress, BluetoothService.SerialPort); blows up with this error {"The requested address is not valid in its context 601D914C50BF:0000110100001000800000805f9b34fb"}.
The only thing I altered in the sample was to find my smart phone, the moto g6. What am I missing?
Before putting a bounty on this question, I need to clarify that I am also looking for documentation or examples of having a desktop computer running Windows 10 be able to receive a file from iOS or Android and without having to use the built-in Bluetooth step by step in Windows 10. I would like to know what to do to correct the error.
I realize there is Command Line Bluetooth, but it would be nice to click a button in a gui and transfer a file using 32Feet.net.
Looks like the issue is because of services that are running on the device https://archive.codeplex.com/?p=32feet
Are you sure that device you are using has SerialPort profile running?
Also, Can you try the following code by using
private void BluetoothClientConnectCallback(IAsyncResult ar)
{
// Write your Call Back Code here
}
static void Main(string[] args)
{
BluetoothClient client = new BluetoothClient();
AllDevices = client.DiscoverDevicesInRange();
foreach (BluetoothDeviceInfo Device in AllDevices)
{
if (Device.DeviceName.Equals("moto g(6)"))
{
if (!client.Connected)
client = new BluetoothClient();
client.BeginConnect(Device.DeviceAddress, Device.InstalledServices[0], this.BluetoothClientConnectCallback, client);
break;
}
}
client.Close();
}
Also, you have to pair your device before connecting. Check here
BluetoothSecurity.PairRequest(Device.DeviceAddress,"123456");
I have a problem here. I created a windows app that requires interaction between browser and desktop apps. In the desktop app, I include WebSocket Secure made by [Dave](WebSocket Server in C#).
I have a valid pfx file. While using the default port (443), everything runs smoothly. The URL shows the CN of the SSL. My window app then has to use other port other than default ones (443), when I change in setting it runs not as per CN of the SSL but instead localhost:portnum. how to make it run using CN in ports other than 443? Please help.
I will try to answer this.
I have checked the link that you have pasted and came across the following code snippet:
private static void Main(string[] args){
IWebSocketLogger logger = new WebSocketLogger();
try
{
string webRoot = Settings.Default.WebRoot;
int port = Settings.Default.Port;
// used to decide what to do with incoming connections
ServiceFactory serviceFactory = new ServiceFactory(webRoot, logger);
using (WebServer server = new WebServer(serviceFactory, logger))
{
server.Listen(port);
Thread clientThread = new Thread(new ParameterizedThreadStart(TestClient));
clientThread.IsBackground = false;
clientThread.Start(logger);
Console.ReadKey();
}
}
catch (Exception ex)
{
logger.Error(null, ex);
Console.ReadKey();
}
}
Within the try block there is this code line:
int port = Settings.Default.Port;
Maybe trying setting that to an auto assign port fix your problem.
Dear Stack Overflow Community,
i am currently developing an online TCG in C#. The server runs perfectly fine on my own machine (quad-core, octa-thread Windows 7). I could connect 12 clients without problem. But when I launch it on a server, the maximum amount of clients becomes limited to the number of processor cores on the machine. I ran the code on a single-core Windows 2016 Server and could not connect more that one client to start a game. Then I ran the server on a quad-core Windows 2012 Server and could only connect four clients and start two games. Any further clients got completely ignored until someone disconnects. Then the new client gets accepted and the server crashes.
The server is a MS Visual Studio 2015 Windows Forms Application with .NET Framework 4.0. The Windows Server machines have .NET Framework 4.0 and my own machine has version 4.5.
I will gladly provide any additional information you may require and answer all your questions.
Server code in C#:
public void Init()
{
try {
server = new TcpListener(IPAddress.Any, port);
server.Start();
serverRunning = true;
server.BeginAcceptTcpClient(AcceptTcpClient, server);
OutputTB.Text = "server has been started on port " + port.ToString();
}
catch (Exception e) {
OutputTB.Text = "socket error: " + e.Message;
}
}
private void AcceptTcpClient(IAsyncResult newClient)
{
if (!serverRunning)
return;
server.BeginAcceptTcpClient(AcceptTcpClient, server);
TcpListener listener = (TcpListener)newClient.AsyncState;
ServerClient client = new ServerClient(listener.EndAcceptTcpClient(newClient));
Send("SWHO", client);
connectedClients.Add(client);
Invoke((MethodInvoker)delegate {
ClientListBox.Items.Add("Waiting for authentification...");
});
NetworkStream stream = client.tcp.GetStream();
StreamReader reader = new StreamReader(stream, true);
while (client.connected && serverRunning) {
if (stream.DataAvailable) {
string data = reader.ReadLine();
if (data != null)
OnIncomingData(client, data);
}
}
Invoke((MethodInvoker)delegate {
if (client.authenticated)
ClientListBox.Items.Remove(client.playerName);
else
ClientListBox.Items.Remove("Waiting for authentification...");
});
Send("SDISC", client);
waitingClients.Remove(client);
connectedClients.Remove(client);
client.tcp.Close();
}
private void OnIncomingData()
{
//process client data
}
Thread pool exhaustion it was! Big thanks to itsme86 and usr for the helpful tips. Now the code looks like this:
private void AcceptTcpClient(IAsyncResult ar)
{
server.BeginAcceptTcpClient(AcceptTcpClient, server);
Task.Run(() => ListenToIncomingData(IAsyncResult ar);
}
There is one thing I'm curious about: doesn't the asynchronous call also consume a thread? how come there are enough resources to handle it but not enough to handle the unfinished callback?
I am listening for connections through a Windows Universal App and would like to connect to that App through a Windows Console Application. I have done some basic code which I think should connect but I get a timeout error from the console application.
{"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 192.168.0.5:1771"}
The windows universal app never even goes into the connection received function.
The Server (UWP):
public async void SetupServer()
{
try
{
//Create a StreamSocketListener to start listening for TCP connections.
Windows.Networking.Sockets.StreamSocketListener socketListener = new Windows.Networking.Sockets.StreamSocketListener();
//Hook up an event handler to call when connections are received.
socketListener.ConnectionReceived += SocketListener_ConnectionReceived;
//Get Our IP Address that we will host on.
IReadOnlyList<HostName> hosts = NetworkInformation.GetHostNames();
HostName myName = hosts[3];
//Assign our IP Address
ipTextBlock.Text = myName.DisplayName+":1771";
ipTextBlock.Foreground = new SolidColorBrush(Windows.UI.Color.FromArgb(255,0,255,0));
//Start listening for incoming TCP connections on the specified port. You can specify any port that' s not currently in use.
await socketListener.BindEndpointAsync(myName, "1771");
}
catch (Exception e)
{
//Handle exception.
}
}
The Client (Console Application):
static void Main(string[] args)
{
try
{
byte[] data = new byte[1024];
int sent;
string ip = "192.168.0.5";
int port = 1771;
IPEndPoint ipep = new IPEndPoint(IPAddress.Parse(ip), port);
TcpClient client = new TcpClient();
client.Connect(ipep); //**************Stalls HERE************
using (NetworkStream ns = client.GetStream())
{
using (StreamReader sr = new StreamReader(ns))
{
using (StreamWriter sw = new StreamWriter(ns))
{
sw.WriteLine("Hello!");
sw.Flush();
System.Threading.Thread.Sleep(1000);
Console.WriteLine("Response: " + sr.ReadLine());
}
}
}
}
catch (Exception e)
{
}
}
I have tested your code on my side and it can work well. So there is nothing wrong with your code. But I can reproduce your issue by running the server and client on the same device, the client will throw the same exception as you showed above. So please ensure you're connecting from another machine. We cannot connect to a uwp app StreamSocketListener from another app or process running on the same machine,this is not allowed. Not even with a loopback exemption.
Please also ensure the Internet(Client&Server) capability is enabled. And on the client you can ping the server 192.168.0.5 successfully.
I'm working to make a Client/Server Application in C# using winsock Control. I done every thing in that but i stuck the place of sending data from client to server. In my program server always listen the client using the ip and port. I send the data from the client to server.
1)When click the Listen button on the server form it open the server where client is connect.
2)In Client form 1st i click the connect button for that the server is connected Gives an message (Connect Event: ip) for this message we easly know that the client is connected to the server.
3)Then we enter some data in the Send Data text Box then click Send Button to send the data to server and also save in client.
Code Below:
SERVER:
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Net;
using System.Threading;
using System.Net.Sockets;
namespace Server
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
const string DEFAULT_SERVER = "ip";
const int DEFAULT_PORT = 120;
System.Net.Sockets.Socket serverSocket;
System.Net.Sockets.SocketInformation serverSocketInfo;
public string Startup()
{
IPHostEntry hostInfo = Dns.GetHostByName(DEFAULT_SERVER);
IPAddress serverAddr = hostInfo.AddressList[0];
var serverEndPoint = new IPEndPoint(serverAddr, DEFAULT_PORT);
serverSocket = new System.Net.Sockets.Socket(System.Net.Sockets.AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Stream, System.Net.Sockets.ProtocolType.Tcp);
serverSocket.Bind(serverEndPoint);
return serverSocket.LocalEndPoint.ToString();
}
public string Listen()
{
int backlog = 0;
try
{
serverSocket.Listen(backlog);
return "Server listening";
}
catch (Exception ex)
{
return "Failed to listen" + ex.ToString();
}
}
public string ReceiveData()
{
System.Net.Sockets.Socket receiveSocket;
byte[] buffer = new byte[256];
receiveSocket = serverSocket.Accept();
var bytesrecd = receiveSocket.Receive(buffer);
receiveSocket.Close();
System.Text.Encoding encoding = System.Text.Encoding.UTF8;
return encoding.GetString(buffer);
}
private void Listen_Click(object sender, EventArgs e)
{
string serverInfo = Startup();
textBox1.Text = "Server started at:" + serverInfo;
serverInfo = Listen();
textBox1.Text = serverInfo;
//string datatosend = Console.ReadLine();
//SendData(datatosend);
serverInfo = ReceiveData();
textBox1.Text = serverInfo;
//Console.ReadLine();
}
private void winsock_DataArrival(object sender, AxMSWinsockLib.DMSWinsockControlEvents_DataArrivalEvent e)
{
ReceiveData();
Listen();
}
private void winsock_ConnectEvent(object sender, EventArgs e)
{
Listen();
}
}
}
This all are work perfectly But here my problem is that i get data form the client to server at only one time. When i send data again from the client to the server its not working and gives me some Message like
Additional information: Only one usage of each socket address
(protocol/network address/port) is normally permitted
In the server form
serverSocket.Bind(serverEndPoint);
Please someone help me to solve my problem.
Thank you.
Try this. It helps you
delegate void AddTextCallback(string text);
public Form1()
{
InitializeComponent();
}
private void ButtonConnected_Click(object sender, EventArgs e)
{
ThreadPool.QueueUserWorkItem(new WaitCallback(ServerHandler));
}
private void ServerHandler(object state)
{
TcpListener _listner = new TcpListener(IPAddress.Parse("12.2.54.658"), 145);
_listner.Start();
AddText("Server started - Listening on port 145");
Socket _sock = _listner.AcceptSocket();
//AddText("User from IP " + _sock.RemoteEndPoint);
while (_sock.Connected)
{
byte[] _Buffer = new byte[1024];
int _DataReceived = _sock.Receive(_Buffer);
if (_DataReceived == 0)
{
break;
}
AddText("Message Received...");
string _Message = Encoding.ASCII.GetString(_Buffer);
AddText(_Message);
}
_sock.Close();
AddText("Client Disconnected.");
_listner.Stop();
AddText("Server Stop.");
}
private void AddText(string text)
{
if (this.listBox1.InvokeRequired)
{
AddTextCallback d = new AddTextCallback(AddText);
this.Invoke(d, new object[] { text });
}
else
{
this.listBox1.Items.Add(text);
}
}
I'm also have the same problem like you on last month but i solve that using this Receive multiple different messages TcpListener C# from stackoverflow. This helps me lot hope it helps to solve your problem also.
I'm not 100% sure you understand TCP sockets so here goes.
When you use a TCP listener socket you first bind to a port so that clients have a fixed, known point to connect to. This reserves the port for your socket until you give it up by calling Close() on that socket.
Next you Listen in order to begin the process of accepting clients on the port you bound to. You can do both this and the first step in one but as you haven't I haven't here.
Next you call Accept(). This blocks (halts execution) until a client connects and then it returns a socket which is dedicated to communication with that client. If you want to allow another client to connect, you have to call Accept() again.
You can then communicate with your client using the socket that was returned by Accept() until you're done, at which point you call Close() on that socket.
When you're done listening for new connections you call Close() on your listener socket.
However when you press your listen button the following happens:
You bind correctly, you begin listening correctly and then your call to ReceiveData() blocks on the Accept call until a client is received. You then receive some data (though this is TCP so that might not be the whole data!) and then you instantly close the connection to your client.
I presume to get the error you're getting you must then press listen again on your server. This therefore restarts the whole listener socket and when you get to bind to the port the second time your previous listener is still bound to it and thus the call fails because something's already allocated on that port.
Solution wise you need to keep the socket returned from the Accept() call open until you're done with it. Have the client handle the close by calling the Shutdown() method on their socket or establish some convention for marking the end of communication.
You're also going to run into trouble when you try and have multiple users connected and so at some point you're either going to require threads or some asynchronous sockets but I feel that's out the scope of this question.
I suggest you do not use AxMSWinsockLib.. Have a look at socket example given here where it shows how to create a client socket and server socket - https://msdn.microsoft.com/en-us/library/kb5kfec7(v=vs.110).aspx AND this one - https://msdn.microsoft.com/en-us/library/6y0e13d3(v=vs.110).aspx