66 lines
3.0 KiB
C#
66 lines
3.0 KiB
C#
using System.Net.Sockets;
|
|
using System.Net;
|
|
|
|
using BCG;
|
|
using System;
|
|
using System.Collections.Generic;
|
|
|
|
|
|
namespace bts {
|
|
// Unlike AsyncTCPConnectionAcceptor_APM this class is static since the requests to connect are stand alone requests
|
|
// whereas AsyncTCPConnectionAcceptor_APM is always listening for incoming connections which lends itself to more
|
|
// statefullness and hence non static
|
|
public static class AsyncTCPConnector_APM {
|
|
|
|
internal class SocketConnectionArgs {
|
|
public EndPoint ep;
|
|
public Socket sock;
|
|
public ITCPConnectionHandler handler;
|
|
public string server_url;
|
|
|
|
internal SocketConnectionArgs(EndPoint theEp, Socket the_sock, ITCPConnectionHandler the_handler,
|
|
string theServerURL) {
|
|
ep = theEp;
|
|
sock = the_sock;
|
|
handler = the_handler;
|
|
server_url = theServerURL;
|
|
}
|
|
|
|
public override string ToString() {
|
|
return $"SocketConnectionArgs: ep: {ep} server_url: {server_url}";
|
|
}
|
|
}
|
|
|
|
public static void connect_to(RemoteConnectionInfo server_address, ITCPConnectionHandler handler) {
|
|
bts.Log.Gen.info($"AsyncTCPConnector_APM.connectTo server: {server_address}");
|
|
// when connection is established, this sock passed to an ITCPCOnnection and sent back
|
|
Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
|
|
EndPoint ip_ep = new IPEndPoint(IPAddress.Parse(server_address.ip), server_address.port);
|
|
sock.BeginConnect(ip_ep, new AsyncCallback(_on_connect),
|
|
new SocketConnectionArgs(ip_ep, sock, handler, server_address.ToString()));
|
|
}
|
|
|
|
private static void _on_connect(IAsyncResult res) {
|
|
Log.Gen.info($"AsyncTCPConnector_APM._on_connect res: {res.AsyncState}");
|
|
SocketConnectionArgs sc_args = res.AsyncState as SocketConnectionArgs;
|
|
try {
|
|
sc_args.sock.EndConnect(res);
|
|
} catch (SocketException socket_ex) {
|
|
bts.Log.Gen.info($"AsyncTCPConnector_APM._on_connect EndConnect failed, args: {sc_args} ex: {socket_ex}");
|
|
if (sc_args.handler.isDisposed) {
|
|
return;
|
|
} else {
|
|
System.Threading.Thread.Sleep(TimeSpan.FromMilliseconds(1000));
|
|
bts.Log.Gen.info($"AsyncTCPConnector_APM retrying connectiont to server: {sc_args.server_url}");
|
|
sc_args.sock.BeginConnect(sc_args.ep, new AsyncCallback(_on_connect), sc_args);
|
|
return;
|
|
}
|
|
}
|
|
bts.Log.Gen.info($"AsyncTCPConnector_APM._on_connect EndConnect successful args: {sc_args}");
|
|
sc_args.handler.onConnection(new AsyncTCPConnection_APM(sc_args.sock, TimeSpan.FromSeconds(1),
|
|
ITCPConnection.ConnectionSide.Client));
|
|
}
|
|
|
|
}
|
|
}
|