Why frontend and server cannot connect through websocket after deployment - c#

After I deployed my app to amazon the connection between my frontend and server via websocket doesn't work. To be more precise, when I open the frontend form the amazon link and run the server on my computer it works, but when someone else tries to use the app from a different ip, messages don't come to the server.
Below, I put fragments of code that establish the connection.
Here is how I connect to the server in the frontend (Angular):
public openWebSocket(port : number){
this.webSocket = new WebSocket('ws://192.168.0.16:' + port.toString());
this.webSocket.onopen = (event) => {
//console.log('Open: ', event);
}
this.webSocket.onmessage = (event) => {
//console.log('Received message: ', event);
const msg : Message = JSON.parse(event.data);
switch(msg.Type){ ...
and here is how I establsh a websocket on the server (C# console app):
public Server(int port)
{
//setup websocket
_port = port;
_webSocket = new WebSocketServer();
RootConfig r = new RootConfig();
ServerConfig s = new ServerConfig();
s.Name = "SuperWebSocket";
s.Ip = "Any";
s.Port = port;
s.Mode = SocketMode.Tcp;
SuperSocket.SocketEngine.SocketServerFactory f = new SuperSocket.SocketEngine.SocketServerFactory();
_webSocket.Setup(r, s, f);
_webSocket.Listeners[0].EndPoint = new IPEndPoint(IPAddress.Parse("192.168.0.16"),port);
_webSocket.NewSessionConnected += Connect;
_webSocket.NewDataReceived += DataReceived;
_webSocket.NewMessageReceived += MessageReceived;
_webSocket.SessionClosed += SessionClosed; ...

Related

Pop3 Authentication Using Proxy

i keep getting authentication failed error after i provide proxy information to Pop3Client. Connection is fine but authentication part gives the following error:
ProxySettings ProxySetting = new ProxySettings
{
Name = "asaf",
Host = "192.168.3.55",
Port = 808,
Auth = new Authorization
{
Type = AuthenticationMethodConstants.Ntlm,
User = "User-001",
Password = "Deneme123"
}
};
using (var client = new Pop3Client())
{
client.Timeout = 120000;
if (ProxySetting != null)
{
client.ProxyClient = ProxySetting.CreateHttpProxyClient();
Console.WriteLine("Current proxy: " + client.ProxyClient.ProxyHost + ":" + client.ProxyClient.ProxyPort);
}
client.ServerCertificateValidationCallback = (s, c, h, e) => true;
client.Connect("outlook.office365.com", 995, SecureSocketOptions.SslOnConnect);
client.Authenticate("mcs234#lenfs.onmicrosoft.com", "phtfg456!");
Interesting thing is that I just tried the same code with ImapClient with port 993 and it worked just fine. It seems problem is only for Pop3 protocol.

PskTlsClient with Bouncy castle, System.IO.IOException on Connect

I'm developing a client-server with psk by openssl.
At the moment the server side is not implemented yet, there is a stub on my Ubuntu Linux machine only for tests purpose as the following:
openssl s_server -accept 9999 -cipher ECDHE-PSK-CHACHA20-POLY1305 -nocert -psk 6161616161 -psk_identity admin
There are some problems on the client side, I'm stuck in a rut because everything seems implemented as the following
class Program
{
private static readonly SecureRandom _secureRandom = new SecureRandom();
internal static TlsClientProtocol OpenTlsConnection(string hostname, int port, Org.BouncyCastle.Crypto.Tls.TlsClient client)
{
var tcp = new TcpClient(hostname, port);
var protocol = new TlsClientProtocol(tcp.GetStream(), _secureRandom);
protocol.Connect(client);
return protocol;
}
static void Main(string[] args)
{
var hostname = "192.168.132.160";
var port = 9999;
var psk_identity = "admin";
// hardcoded psk
var psk = new byte[] { 0x61, 0x61, 0x61, 0x61, 0x61 };
var pskIdentity = new BasicTlsPskIdentity(psk_identity, psk);
var client = new PskTlsClient(null, pskIdentity);
var protocol = OpenTlsConnection(hostname, port, client);
// Tryng to send something
var req = Encoding.UTF8.GetBytes("GET / HTTP/1.1\r\n\r\n");
var tlsStream = protocol.Stream;
tlsStream.Write(req, 0, req.Length);
tlsStream.Flush();
var reader = new StreamReader(tlsStream);
string line;
while ((line = reader.ReadLine()) != null)
{
Console.WriteLine(">>> " + line);
}
protocol.Close();
}
}
I get this exception every time:
System.IO.IOException: 'Unable to read data from the transport
connection: 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.'
In addition, this code on my Linux Machine works
openssl s_client -connect 192.168.132.160:9999 -psk 6161616161 -psk_identity admin -tls1_2
Did I miss something on my client side? Can anyone help me? I'm going mad.
Thanks
PskTlsClient only provides some cipher by default, to add what I wanted I develop a little proxy (design pattern) of PskTlsClient overriding GetCipherSuites() as the following:
public class PskTlsClientProxy : PskTlsClient
{
public PskTlsClientProxy(TlsPskIdentity pskIdentity) : base(pskIdentity)
{
}
public PskTlsClientProxy(TlsCipherFactory cipherFactory, TlsPskIdentity pskIdentity) : base(cipherFactory, pskIdentity)
{
}
public PskTlsClientProxy(TlsCipherFactory cipherFactory, TlsDHVerifier dhVerifier, TlsPskIdentity pskIdentity) : base(cipherFactory, dhVerifier, pskIdentity)
{
}
public override void NotifyServerVersion(ProtocolVersion serverVersion)
{
base.NotifyServerVersion(serverVersion);
Console.WriteLine("TLS-PSK client negotiated " + serverVersion);
}
public override int[] GetCipherSuites()
{
return new int[] {
CipherSuite.DRAFT_TLS_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256,
};
}
}

SSL enabled Web Site can't connect to Local C# Web Socket Server

I'm using a local web socket server implemented in C#. Its working fine when I connect to hosted html page without SSL, but when there is SSL enabled, Web socket connection closed automatically.
In the readMe.txt file of the library, it says to attach a certification file.
Here is how I create and attach the file. Right click the Project and do Sign the Manifest and gave a password. Then I have set the Certification property as follows.
WebSocketServer server = new WebSocketServer("wss://0.0.0.0:8431");
string path = "C:\\Users\\Dehan\\Documents\\MySolutionName\\";
server.Certificate = new X509Certificate2(path+"certificateName.pfx", "certificate_pwd", X509KeyStorageFlags.MachineKeySet);
server.Start(socket =>
{
socket.OnOpen = () =>
{
//inside onopen
};
socket.OnError = error =>
{
//inside onerror
};
socket.OnClose = () =>
{
//inside onclose
};
socket.OnMessage = message =>
{
//inside onmessage
}
});
following code shows the javascript of the html page
<script type="text/javascript">
var start = function () {
var inc = document.getElementById('incomming');
var wsImpl = window.WebSocket || window.MozWebSocket;
var form = document.getElementById('sendForm');
var input = document.getElementById('sendText');
inc.innerHTML += "connecting to server ..<br/>";
// create a new websocket and connect
window.ws = new wsImpl('wss://127.0.0.1:8431/');
// when data is comming from the server, this metod is called
ws.onmessage = function (evt) {
inc.innerHTML += evt.data + '<br/>';
};
// when the connection is established, this method is called
ws.onopen = function () {
inc.innerHTML += '.. connection open<br/>';
};
// when the connection is closed, this method is called
ws.onclose = function () {
inc.innerHTML += '.. connection closed<br/>';
}
form.addEventListener('submit', function(e){
e.preventDefault();
var val = input.value;
ws.send(val);
input.value = "";
});
}
window.onload = start;
</script>
server.Certificate = new X509Certificate2(path+"certificateName.pfx", "certificate_pwd", X509KeyStorageFlags.MachineKeySet);
In the above line of code, If you're using a self signed certificate make sure that it is added to your computers trusted root authorities.

cocoaasynsocket to c sharp server

I want to communicate between iPhone and C# server through Sockets,
When I try to create socket from iPhone to my C Sharp server over a LAN using cocoaasynsockets, but it does not create any socket on my server. I tried giving different IPs like 127.0.0.1/192.168.2.102(local)/IP found on (whatispmyip.com), but no gain,
here is my testing code for iPhone
- (IBAction)connect:(id)sender{
GCDAsyncSocket *socket;
socket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
NSError *err = nil;
if (![socket connectToHost:#"192.168.2.102" onPort:52523 error:&err]) // Asynchronous!
{
NSLog(#error : %#"", err);
}
}
- (void)socket:(GCDAsyncSocket *)sender didConnectToHost:(NSString *)host port:(UInt16)port
{
NSLog(#"connected");
}
and here is my c sharp server code
TcpListener _tcpListerner;
public void startingServer() {
// IPAddress ipad = Dns.Resolve("localhost").AddressList[0];
IPAddress ipad = IPAddress.Parse("192.168.2.102");
_tcpListerner = new TcpListener(ipad, 52523);
_tcpListerner.Start();
Console.WriteLine("The local End point is :" +_tcpListerner.LocalEndpoint);
Console.WriteLine("Waiting for a connection.....");
Thread thread = new Thread(acceptClients);
thread.Start();
}
void acceptClients()
{
Socket s = _tcpListerner.AcceptSocket();
Console.WriteLine("Connection accepted from " + s.RemoteEndPoint);
byte[] b = new byte[100];
int k = s.Receive(b);
char cc = ' ';
string test = null;
Console.WriteLine("Recieved...");
for (int i = 0; i < k - 1; i++)
{
Console.Write(Convert.ToChar(b[i]));
cc = Convert.ToChar(b[i]);
test += cc.ToString();
}
What I am missing in it, what IP should I give, or there is some settings on server side or on iphone(client side) to accept/create socket from network
Use IPAddress.Any on the server to listen on all machine addresses.
On the client side use the LAN address of the server you want to connect to.

Udp packets to machine behind nat

First of all sry about my english. My problem is i have electronic circuit on press machine. This circuit sending data to my server without a problem. After i recieve data i need to send command to circuit. In LAN its working like a charm. But out of lan circuit dont recieving my command somehow. Any idea how i can send to udp pocked to machine behind NAT ? my code is bellow , ty for any help.
private void ReceiveMessage()
{
while (true)
{
try
{
var remoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
var content = _udpClient.Receive(ref remoteIpEndPoint);
if (content.Length > 0)
{
var message = Encoding.ASCII.GetString(content);
var smsg = message.Split('|');
var pin1 = int.Parse(smsg[13]);
var pin2 = int.Parse(smsg[14]);
var isChanged = CheckChanges(smsg[1]);
if (isChanged == 1)
{
**var recvpt = new IPEndPoint(remoteIpEndPoint.Address, remoteIpEndPoint.Port);
var client = new UdpClient();
var cmd1 = "CP1S" + _pin1Time + "F";
var cmd2 = "CP2S" + _pin2Time + "F";
var senddata1 = Encoding.UTF8.GetBytes(cmd1);
var senddata2 = Encoding.UTF8.GetBytes(cmd2);
client.Send(senddata1, senddata1.Length, recvpt);
client.Send(senddata2, senddata2.Length, recvpt);
client.Close();**
// UpdateChanges(smsg[1]);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToStrin<wbr ></wbr>g());
}
}
}
}
Computers that are behind a NAT router are not directly accessible from a remote network. There would need to be rules put in place on your firewall/router to route this traffic to the remote machine. For explicit directions see your WAN/LAN admin. If you don't have one you could try asking over on Server Fault with more information about your network.

Categories