I can't connect to my WebSocket C# Server with a C# Application with websocket.
I have a server with Fleck Websocket Server.
Before Windows update my app connected to my server without problem. (Not sure if Windows update is the problem) But this update make me update the TLS of the server to TLS 1.2 .
This is the code that allowed me to connect to the server (before the bug) :
using (var socket = new ClientWebSocket())
try
{
await socket.ConnectAsync(new Uri(string.Format("wss://myip:myport", ip, port)), CancellationToken.None);
webSocket = socket;
server = string.Format("{0}:{1}", ip, port);
SocketConnected = true;
OnSocketStateChanged?.Invoke(socket, new SocketStateChangeEventArgs() { Server = string.Format("{0}:{1}", ip, port) });
await Receive(socket);
}
catch (Exception ex)
{
SocketConnected = false;
OnSocketStateChanged?.Invoke(socket, new SocketStateChangeEventArgs() { Server = string.Format("{0}:{1}", ip, port) });
Console.WriteLine($"ERROR - {ex.Message}");
Thread.Sleep(1000);
}
} while (true);
I can still connect with a web application on my server and it works perfectly.
http://www.websocket.org/echo.html works too.
I tryied to change the connection method, so i have downloaded WebSocketSharp from nugget package for tryied another way to connect but it still doesn't work.
using (var ws = new WebSocket("wss://myip:myport"))
{
ws.OnMessage += Ws_OnMessage;
ws.OnOpen += Ws_OnOpen;
ws.OnClose += Ws_OnClose;
ws.OnError += Ws_OnError;
webSocket = ws;
ws.Connect();
}
My IP and Port are good, same values than the web Application.
I got no error in every case, but i'm still not connected, nothing on the server too.
My C# application works with .NET Framework 4.5.2.
No Firewall problem.
Thank you for your help and sorry for my bad english.
Related
When client and server work on same pc they connect fine.
Next situation is server on real pc, client on VirtualBox. Both devices have Windows 10. Firewall is disabled on server. When client tries to connet to server exception occurs:
Grpc.Core.RpcException: 'Status(StatusCode="Internal", Detail="Error
starting gRPC call.
Client code:
public ThermocyclerClient()
{
AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true);
var httpClientHandler = new HttpClientHandler
{
ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator
};
var httpClient = new HttpClient(httpClientHandler);
var channel = GrpcChannel.ForAddress("http://192.168.111.189:7001", new GrpcChannelOptions { HttpClient = httpClient });
client = new ThermocyclerRpcService.ThermocyclerRpcServiceClient(channel);
}
Server code:
server = new Server
{
Ports = { new ServerPort("localhost", 7001, ServerCredentials.Insecure) },
Services =
{
ExtractorRpcService.BindService(this.extractorService),
ThermocyclerRpcService.BindService(this.thermocyclerService)
}
};
Why client can't connect to server?
Real pc and VirtualBox ping each over successfully.
The correct answer was given by Marc Gravell in comments. Changing from localhost to computer name has helped. "0.0.0.0" in host name also works (thanks to zanseb).
I have a gRPC client calling into a server on the same machine and client code uses the channel created with:
Channel channel = new Channel("localhost", 11112, ChannelCredentials.Insecure);
This works well, and I'm getting the reply as expected.
However, if I replace "localhost" with the actual machine name (FQDN) or IP address, I'm getting an error:
Status(StatusCode="Unavailable", Detail="failed to connect to all addresses", DebugException="Grpc.Core.Internal.CoreErrorDetailException: {"created":"#1616190440.553000000","description":"Failed to pick subchannel","file":"..\..\..\src\core\ext\filters\client_channel\client_channel.cc","file_line":5397,"referenced_errors":[{"created":"#1616190440.553000000","description":"failed to connect to all addresses","file":"..\..\..\src\core\ext\filters\client_channel\lb_policy\pick_first\pick_first.cc","file_line":398,"grpc_status":14}]}")
I also tested starting the server on a remote machine and having the client call into that remote machine (by name or IP) when creating the channel, but got the same failure.
The application is written in C# .NET Core 3.2 as a Console application. Nuget packages included are: Google.Protobuf, Grpc.Core, Grpc.Tools.
Not sure what is wrong in my code or whether something is not setup properly on my machine.
Here's the reset of the relevant client code:
MWCS.McpsServer.McpsServerClient client = new MWCS.McpsServer.McpsServerClient(channel);
var data = new ProcessResponseInput() { ClientID = clientID };
var options = new CallOptions();
try {
var res = client.ProcessResponse(data, options);
return res;
} catch (RpcException ex) {
StandardOutput so = new StandardOutput() { ExitCode = 1, Message = ex.Message };
return so;
}
To resolve this, I actually had to fix the server code. I should have used "0.0.0.0" instead of "localhost" in the bind address on the server. Looks like when setting the server to localhost it is not visible outside the computer.
Here's how I have the server started now (after the replacement):
_server = new Server() {
Services = { McpsServer.BindService(new McpcServerImplementation()) },
Ports = { new ServerPort("0.0.0.0", 11112, ServerCredentials.Insecure) }
};
I am wokring on a C# application that communicates with a node.js server via a secure websocket. There is also a javascript client that connects to the same websocket hosted on the node server. The javascript client connects successfully connects to the node server. However the c# application throws the error described in the title.
I used the SimpleWebSocketClient extension for chrome to connect to my socket. This works fine.
I also tried websocket4net for the C# application. This doesn't work either.
I used the wss://echo.websocket.org websocket with my c# application and it works fine. However I have to set _socket.SslConfiguration.EnabledSslProtocols = System.Security.Authentication.SslProtocols.tls12;
The Node Server
const app = require('express')()
const fs = require("fs"); // file system core module
var https = require("https").createServer({
cert: fs.readFileSync(__dirname + "/certs/cert.pem"),
key: fs.readFileSync(__dirname + "/certs/key.pem")
}, app)
const express = require("express"); // web framework external module
// Setup and configure Express http server. Expect a subfolder called "static" to be the web root.
app.use(express.static(__dirname + "/static/"));
const ws = require('ws')
const wss = new ws.Server({
server: https
});
wss.on('connection', function connection(ws) {
ws.on('message', function incoming(message) {
console.log('received: %s', message);
ws.send('reply from server : ' + message)
});
ws.send('something');
});
// Listen on port 8080
https.listen(8080, () => {
console.log('listening on https://localhost:8080')
})
And here is the C# Code
_socket = new WebSocket("wss://127.0.0.1:8080");
_id = Guid.NewGuid().ToString();
_socket.OnOpen += (sender, e) =>
{
Console.WriteLine("WebSocket Connection is now Open with ID: " + _id);
};
_socket.OnMessage += (sender, e) =>
{
Console.WriteLine("On Message");
Console.WriteLine(e.Data);
};
_socket.Connect();
I'm confused why my C# application doesn't work. It should be able to build a connection just like with wss://echo.websocket.org
I have a simple code that I am testing against a socket.io server (chat.socket.io)
IO.Options testOptions = new IO.Options();
string url = "http://chat.socket.io";
testOptions.ForceNew = true;
testOptions.AutoConnect = true;
testOptions.Upgrade = true;
Socket _socket = IO.Socket(url, testOptions);
_socket.On("data", (data) =>
{
Console.WriteLine(data.ToString());
});
When I look at the connection through fiddler I see the transport is only polling
I have no Idea why
Also about every 2 minutes the client disconnects and reconnects
I'm making a api service which connects to a SSL TCP server to retrieve data. I first made this api in C# and it works. Later I ported it to node.js to take the advantages of node.js. However I couldn't connect to the server.
Target :
Host : prodtw.lol.garenanow.com
Port : 2099
Code in C# which can connect to the server and works perfectly:
TcpClient client;
try
{
client = new TcpClient("prodtw.lol.garenanow.com", 2099);
Console.WriteLine("Connected to server.");
}
catch
{
Console.WriteLine("Error");
return;
}
SslStream sslStream = new SslStream(client.GetStream(), false, AcceptAllCertificates); //AcceptAllCertificate does nothing, just return true
var ar = sslStream.BeginAuthenticateAsClient("prodtw.lol.garenanow.com", null, null);
using (ar.AsyncWaitHandle)
{
if (ar.AsyncWaitHandle.WaitOne(-1))
sslStream.EndAuthenticateAsClient(ar);
}
// Connected, write something
byte[] handshakePacket = new byte[1537];
sslStream.Write(handshakePacket);
Code in node.js, which couldn't connect to the SSL TCP server :
var tls = require('tls');
console.log('Connecting');
var stream = tls.connect(2099, "prodtw.lol.garenanow.com", function() {
console.log('Successfully connected!'); //Never print this message.
});
After running the above node.js code, it never shows "Successfully connected". It only shows "Connecting" and stucks at tls.connect...