Here are the examples of the csharp api System.Net.IPAddress.Parse(string) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
1807 Examples
19
Source : MemcachedIo.cs
with MIT License
from 0ffffffffh
with MIT License
from 0ffffffffh
public bool AttachMemcachedInstance(MemcachedInstance instance)
{
if (!instance.IsRunning)
return false;
MemcachedClientConfiguration conf = new MemcachedClientConfiguration();
this.serverIp = new IPEndPoint(IPAddress.Parse("127.0.0.1"), instance.Port);
conf.Protocol = MemcachedProtocol.Binary;
conf.Servers.Add(this.serverIp);
this.mc = new MemcachedClient(conf);
this.instance = instance;
return true;
}
19
Source : LogService.cs
with MIT License
from 0ffffffffh
with MIT License
from 0ffffffffh
public static void Start()
{
IPAddress localIp = IPAddress.Parse("127.0.0.1");
sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
localEp = new IPEndPoint(localIp, 2019);
sock.Bind(localEp);
logFile = new LogFileWriter("sozlukcgi-bridge");
worker = new Thread(new ThreadStart(Recv));
worker.Start();
}
19
Source : ServerInfo.cs
with MIT License
from 1ZouLTReX1
with MIT License
from 1ZouLTReX1
private void Awake()
{
if (ipAddressString != "")
ipAddress = IPAddress.Parse(ipAddressString);
else
ipAddress = Globals.GetLocalIPAddress();
localEP = new IPEndPoint(ipAddress, port);
}
19
Source : Program.cs
with MIT License
from 1iveowl
with MIT License
from 1iveowl
static async Task UdpMulticastListenerTest()
{
var localHost = IPAddress.Parse("192.168.0.59");
var multicastIpAddress = IPAddress.Parse("239.255.255.250");
var ipEndpoint = new IPEndPoint(localHost, 8000);
var udpClient = new UdpClient
{
ExclusiveAddressUse = false
};
udpClient.JoinMulticastGroup(multicastIpAddress);
udpClient.Client.Bind(ipEndpoint);
udpClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
var cts = new CancellationTokenSource();
var disposable = udpClient
.ToHttpListenerObservable(cts.Token)
.Subscribe(msg =>
{
Console.WriteLine($"Remote Address: {msg.RemoteIpEndPoint.Address}");
Console.WriteLine($"Remote Port: {msg.RemoteIpEndPoint.Port}");
Console.WriteLine($"Local Address: {msg.LocalIpEndPoint.Address}");
Console.WriteLine($"Local Port: {msg.LocalIpEndPoint.Port}");
msg.Body.WriteToConsole();
Console.WriteLine("--------------***-------------");
},
ex =>
{
},
() =>
{
});
await Task.CompletedTask;
}
19
Source : Resp3HelperTests.cs
with MIT License
from 2881099
with MIT License
from 2881099
public static RedisSocket GetRedisSocket()
{
var endpoint = new IPEndPoint(IPAddress.Parse("192.168.164.10"), 6379);
var _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
_socket.Connect(endpoint);
return new RedisSocket(_socket);
}
19
Source : DefaultRedisSocket.cs
with MIT License
from 2881099
with MIT License
from 2881099
public void Connect()
{
lock (_connectLock)
{
ResetHost(Host);
IPEndPoint endpoint = IPAddress.TryParse(_ip, out var tryip) ?
new IPEndPoint(tryip, _port) :
new IPEndPoint(Dns.GetHostAddresses(_ip).FirstOrDefault() ?? IPAddress.Parse(_ip), _port);
var localSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
var asyncResult = localSocket.BeginConnect(endpoint, null, null);
if (!asyncResult.AsyncWaitHandle.WaitOne(ConnectTimeout, true))
throw new TimeoutException("Connect to redis-server timeout");
_socket = localSocket;
_stream = new NetworkStream(Socket, true);
_socket.ReceiveTimeout = (int)ReceiveTimeout.TotalMilliseconds;
_socket.SendTimeout = (int)SendTimeout.TotalMilliseconds;
Connected?.Invoke(this, new EventArgs());
}
}
19
Source : NetworkSocket.cs
with BSD 3-Clause "New" or "Revised" License
from 3gstudent
with BSD 3-Clause "New" or "Revised" License
from 3gstudent
public void Connect(string host, int port)
{
// TcpClient
tcpClient = new TcpClient();
tcpClient.SendTimeout = Options.SocketTimeout;
tcpClient.ReceiveTimeout = Options.SocketTimeout;
tcpClient.Connect(IPAddress.Parse(host), port);
// NetworkStream
networkStream = tcpClient.GetStream();
networkStream.WriteTimeout = Options.SocketTimeout;
networkStream.ReadTimeout = Options.SocketTimeout;
}
19
Source : ClientNetworkManager.cs
with MIT License
from 404Lcc
with MIT License
from 404Lcc
public void InitManager(ICenterHandler iCenterHandler, string ip, int port)
{
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
this.iCenterHandler = iCenterHandler;
this.ip = ip;
this.port = port;
socket.Connect(new IPEndPoint(IPAddress.Parse(ip), port));
}
19
Source : SocketServiceImpl.cs
with MIT License
from 499116344
with MIT License
from 499116344
public void RefreshHost(string host)
{
_host = host;
_point = new IPEndPoint(IPAddress.Parse(_host), _port);
}
19
Source : SdkWrapper.cs
with MIT License
from 8bitbytes
with MIT License
from 8bitbytes
private void CreateClient()
{
_ipAddress = IPAddress.Parse("10.30.54.81");
//_ipAddress = IPAddress.Parse("192.168.1.12");
_endpoint = new IPEndPoint(_ipAddress, 8889);
_udpClient = new TelloUdpClient(_ipAddress,_endpoint);
}
19
Source : UdpClient.cs
with MIT License
from a11s
with MIT License
from a11s
public void Connect(string ip, int port, bool CreateBackgroundThread)
{
Connect(new IPEndPoint(IPAddress.Parse(ip), port), CreateBackgroundThread);
}
19
Source : ClientForm1.cs
with MIT License
from a11s
with MIT License
from a11s
private void button_init_Click(object sender, EventArgs e)
{
if (client != null)
{
client.Close();
}
if (cb_isUdp.Checked)
{
client = new k.UdpClient("Test".ToCharArray().Select(a => (byte)a).ToArray(), 0, "udppeer".ToCharArray().Select(a => (byte)a).ToArray());
}
else
{
if (cb_unreliable.Checked)
{
client = new k.KcpClientEx("Test".ToCharArray().Select(a => (byte)a).ToArray(), 0, "mixpeer".ToCharArray().Select(a => (byte)a).ToArray());
}
else
{
client = new k.KcpClient("Test".ToCharArray().Select(a => (byte)a).ToArray(), 0, "kcppeer".ToCharArray().Select(a => (byte)a).ToArray());
}
}
var userid = uint.Parse(textBox_sid.Text);
var arr = textBox_local.Text.Split(":"[0]);
localipep = new IPEndPoint(IPAddress.Parse(arr[0]), int.Parse(arr[1]));
arr = textBox_remote.Text.Split(":"[0]);
remoteipep = new IPEndPoint(IPAddress.Parse(arr[0]), int.Parse(arr[1]));
client.OnOperationResponse = (buf) =>
{
if (cb_isUdp.Checked)
{
var i = BitConverter.ToInt64(buf, 0);
Console.Write($"rec:{i}");
Task.Run(() =>
{
var snd = i + 1;
Console.WriteLine($"udp snd:{snd}");
client.SendOperationRequest(BitConverter.GetBytes(snd));
}
);
}
else
{
if (cb_unreliable.Checked)//is unreliable
{
if (buf.Length == sizeof(UInt64))
{
var i = BitConverter.ToInt64(buf, 0);
Console.Write($"rec:{i}");
Task.Run(() =>
{
var snd = i + 1;
Console.WriteLine($"unreliable snd:{snd}");
clientex?.SendOperationRequest(BitConverter.GetBytes(snd), true);
}
);
}
else
{
//
Console.WriteLine($"{nameof(CheckBigBBuff)}={CheckBigBBuff(buf)} size:{buf.Length} reliable");
}
}
else
{
Console.WriteLine($"{nameof(CheckBigBBuff)}={CheckBigBBuff(buf)} size:{buf.Length} client or clientex.reliable");
}
}
};
client.OnConnected = (sid) =>
{
this.Invoke(
new Action(() =>
{
this.Text = sid.ToString();
})
);
};
client.Connect(remoteipep, true);
}
19
Source : ClientKcp.cs
with MIT License
from a11s
with MIT License
from a11s
private void button_init_Click(object sender, EventArgs e)
{
if (client != null)
{
client.Close();
}
client = new k.KcpClient("Test".ToCharArray().Select(a => (byte)a).ToArray(), 0, "kcppeer".ToCharArray().Select(a => (byte)a).ToArray());
var arr = textBox_remote.Text.Split(":"[0]);
remoteipep = new IPEndPoint(IPAddress.Parse(arr[0]), int.Parse(arr[1]));
client.OnOperationResponse = (buf) =>
{
Console.WriteLine($"{nameof(CheckBigBBuff)}={CheckBigBBuff(buf)} size:{buf.Length} ");
};
client.OnConnected = (sid) =>
{
this.Invoke(
new Action(() =>
{
this.Text = sid.ToString();
})
);
};
client.Connect(remoteipep, true);
}
19
Source : ClientKcp.cs
with MIT License
from a11s
with MIT License
from a11s
private void button_pingpong_init_Click(object sender, EventArgs e)
{
if (client != null)
{
client.Close();
}
client = new k.KcpClient("Test".ToCharArray().Select(a => (byte)a).ToArray(), 0, "kcppeerflush".ToCharArray().Select(a => (byte)a).ToArray());
var arr = textBox_remote.Text.Split(":"[0]);
remoteipep = new IPEndPoint(IPAddress.Parse(arr[0]), int.Parse(arr[1]));
client.OnOperationResponse = ReqArrival;
client.OnConnected = (sid) =>
{
this.Invoke(
new Action(() =>
{
this.Text = sid.ToString();
})
);
};
withflush = checkBox_withflush.Checked == true;
client.Connect(remoteipep, false);
}
19
Source : ClientMix.cs
with MIT License
from a11s
with MIT License
from a11s
private void button_init_Click(object sender, EventArgs e)
{
if (client != null)
{
client.Close();
}
client = new k.KcpClientEx("Test".ToCharArray().Select(a => (byte)a).ToArray(), 0, "mixpeer".ToCharArray().Select(a => (byte)a).ToArray());
var arr = textBox_remote.Text.Split(":"[0]);
remoteipep = new IPEndPoint(IPAddress.Parse(arr[0]), int.Parse(arr[1]));
client.OnOperationResponse = (buf) =>
{
if (buf.Length == sizeof(UInt64))
{
var i = BitConverter.ToInt64(buf, 0);
Console.WriteLine($"rec unreliable:{i}");
}
else
{
Console.WriteLine($"rec reliable {nameof(CheckBigBBuff)}={CheckBigBBuff(buf)} size:{buf.Length} ");
}
};
client.OnConnected = (sid) =>
{
this.Invoke(
new Action(() =>
{
this.Text = sid.ToString();
})
);
};
client.Connect(remoteipep, true);
}
19
Source : ClientUdp.cs
with MIT License
from a11s
with MIT License
from a11s
private void button_init_Click(object sender, EventArgs e)
{
if (client != null)
{
client.Close();
}
client = new k.UdpClient("Test".ToCharArray().Select(a => (byte)a).ToArray(), 0, "udppeer".ToCharArray().Select(a => (byte)a).ToArray());
var arr = textBox_remote.Text.Split(":"[0]);
remoteipep = new IPEndPoint(IPAddress.Parse(arr[0]), int.Parse(arr[1]));
client.OnOperationResponse = (buf) =>
{
var i = BitConverter.ToInt64(buf, 0);
//Console.Write($"rec:{i}");
Task.Run(() =>
{
var snd = i + 1;
Console.WriteLine($"udp snd:{snd}");
client.SendOperationRequest(BitConverter.GetBytes(snd));
}
);
};
client.OnConnected = (sid) =>
{
this.Invoke(
new Action(() =>
{
this.Text = sid.ToString();
})
);
};
client.Connect(remoteipep, true);
}
19
Source : ServerForm1.cs
with MIT License
from a11s
with MIT License
from a11s
private void button_start_Click(object sender, EventArgs e)
{
if (Server != null)
{
throw new InvalidOperationException("Already started");
}
var arr = textBox1.Text.Split(":"[0]);
int port = 1000;
if (arr.Length > 1)
{
port = int.Parse(arr[1]);
}
IPEndPoint ipep = new IPEndPoint(IPAddress.Parse(arr[0]), port);
StartServer(ipep);
}
19
Source : Form1.cs
with MIT License
from a11s
with MIT License
from a11s
private void button_start_Click(object sender, EventArgs e)
{
if (Server != null)
{
throw new InvalidOperationException("Already started");
}
var arr = textBox1.Text.Split(":"[0]);
int port = 1000;
if (arr.Length > 1)
{
port = int.Parse(arr[1]);
}
IPEndPoint ipep = new IPEndPoint(IPAddress.Parse(arr[0]), port);
StartServer(ipep);
}
19
Source : Program.cs
with MIT License
from a11s
with MIT License
from a11s
[STAThread]
static void Main()
{
Console.WriteLine(Environment.OSVersion.Platform);
Console.WriteLine(Environment.OSVersion.VersionString);
Console.WriteLine("All test:");
Console.WriteLine("1 PureUdp test");
Console.WriteLine("2 PureKcp test");
Console.WriteLine("3 Udp+Kcp mix test");
Console.WriteLine("other: exit");
string input = "";
Console.WriteLine("input 1~3:");
input = Console.ReadLine();
switch (input.Trim())
{
case "0":
StartServer = StartServer0;
break;
case "1":
StartServer = StartServer1;
break;
case "2":
StartServer = StartServer2;
break;
case "3":
StartServer = StartServer3;
break;
default:
return;
break;
}
Console.Write("Input ip and port:");
var str = Console.ReadLine();
if (string.IsNullOrWhiteSpace(str))
{
str = "0.0.0.0:1000";
}
var arr = str.Split(":"[0]);
int port = 1000;
if (arr.Length > 1)
{
port = int.Parse(arr[1]);
}
IPEndPoint ipep = new IPEndPoint(IPAddress.Parse(arr[0]), port);
StartServer(ipep);
Console.WriteLine("Press ENTER to close");
Thread updatethread = new Thread(
() =>
{
SpinWait sw = new SpinWait();
while (App.ApplicationRunning)
{
Server?.Service();
sw.SpinOnce();
}
}
);
updatethread.IsBackground = true;
updatethread.Name = $"{nameof(updatethread)}";
updatethread.Start();
while (true)
{
var c = Console.ReadKey(false);
if (c.Key == ConsoleKey.Enter)
{
break;
}
}
Console.WriteLine("closing..");
Server?.Close(TimeSpan.FromSeconds(10));
var servertype = Server.GetType().Name;
Server?.Close(TimeSpan.FromSeconds(10));
Console.WriteLine($"Server {servertype} Closed. Press any to to exit");
Console.ReadKey();
}
19
Source : Test.cs
with MIT License
from a11s
with MIT License
from a11s
void Start()
{
ConnetBtn.onClick.AddListener(() =>
{
if (client != null)
{
client.Close();
}
client = new k.KcpClientEx("Test".ToCharArray().Select(a => (byte)a).ToArray(), 0, "mixpeer".ToCharArray().Select(a => (byte)a).ToArray());
var arr = IPPort.text.Split(":"[0]);
remoteipep = new IPEndPoint(IPAddress.Parse(arr[0]), int.Parse(arr[1]));
client.OnOperationResponse = (buf) =>
{
if (buf.Length == sizeof(UInt64))
{
var i = BitConverter.ToInt64(buf, 0);
//Console.WriteLine($"rec unreliable:{i}");
Console.text += string.Format("rec unreliable:{0}\n", i);
}
else
{
//Console.WriteLine($"rec reliable {nameof(CheckBigBBuff)}={CheckBigBBuff(buf)} size:{buf.Length} ");
Console.text += string.Format("rec unreliable:{0}={1} size:{2}\n", "CheckBigBBuff", Utilities.MakeTestBuff.CheckBigBBuff(buf), buf.Length);
}
};
client.OnConnected = (sid) =>
{
this.replacedle.text = sid.ToString();
};
client.Connect(remoteipep, false);
});
CloseBtn.onClick.AddListener(() =>
{
client.Close();
client = null;
});
Send1Btn.onClick.AddListener(() =>
{
client.SendOperationRequest(Utilities.MakeTestBuff.MakeBigBuff());
});
Send2Btn.onClick.AddListener(() =>
{
client.SendOperationRequest(BitConverter.GetBytes((UInt64)1), true);
});
}
19
Source : Program.cs
with MIT License
from a1q123456
with MIT License
from a1q123456
static void Main(string[] args)
{
RtmpServer server = new RtmpServerBuilder()
.UseStartup<Startup>()
.UseWebSocket(c =>
{
c.BindEndPoint = new IPEndPoint(IPAddress.Parse("0.0.0.0"), 8080);
})
.Build();
var tsk = server.StartAsync();
tsk.Wait();
}
19
Source : ApplicationContext.cs
with Apache License 2.0
from AantCoder
with Apache License 2.0
from AantCoder
internal bool RegisterNewServer(Chanel2Server server, SessionClientWrapper sessionClient)
{
var apadr = IPAddress.Parse(server.IP);
var endPoint = new IPEndPoint(apadr, server.Port);
var result =
OCServerToDiscrord.TryAdd(endPoint, server.Id) &&
UserOnServers.TryAdd(server.Id, new ConcurrentDictionary<ulong, OCUser>());
result &= DiscrordToOCServer.TryAdd(server.Id, sessionClient);
// if sessionClient.IsLogined then must be registred in DataBase
if (sessionClient.IsLogined)
{
result &= _repositoryChanel2Server.AddNewItem(server);
}
else
{
result &= sessionClient.ConnectAndLogin();
}
return result;
}
19
Source : FdbConverters.cs
with MIT License
from abdullin
with MIT License
from abdullin
private static void RegisterDefaultConverters()
{
//TODO: there is too much generic type combinations! need to refactor this ...
RegisterUnsafe<bool, Slice>((value) => Slice.FromByte(value ? (byte)1 : default(byte)));
RegisterUnsafe<bool, byte[]>((value) => Slice.FromByte(value ? (byte)1 : default(byte)).GetBytes());
RegisterUnsafe<bool, string>((value) => value ? "true" : "false");
RegisterUnsafe<bool, sbyte>((value) => value ? (sbyte)1 : default(sbyte));
RegisterUnsafe<bool, byte>((value) => value ? (byte)1 : default(byte));
RegisterUnsafe<bool, short>((value) => value ? (short)1 : default(short));
RegisterUnsafe<bool, ushort>((value) => value ? (ushort)1 : default(ushort));
RegisterUnsafe<bool, int>((value) => value ? 1 : default(int));
RegisterUnsafe<bool, uint>((value) => value ? 1U : default(uint));
RegisterUnsafe<bool, long>((value) => value ? 1L : default(long));
RegisterUnsafe<bool, ulong>((value) => value ? 1UL : default(ulong));
RegisterUnsafe<bool, double>((value) => value ? 0.0d : 1.0d);
RegisterUnsafe<bool, float>((value) => value ? 0.0f : 1.0f);
RegisterUnsafe<int, Slice>((value) => Slice.FromInt32(value));
RegisterUnsafe<int, byte[]>((value) => Slice.FromInt32(value).GetBytes());
RegisterUnsafe<int, string>((value) => value.ToString(CultureInfo.InvariantCulture)); //TODO: string table!
RegisterUnsafe<int, bool>((value) => value != 0);
RegisterUnsafe<int, sbyte>((value) => checked((sbyte)value));
RegisterUnsafe<int, byte>((value) => checked((byte)value));
RegisterUnsafe<int, short>((value) => checked((short)value));
RegisterUnsafe<int, ushort>((value) => checked((ushort)value));
RegisterUnsafe<int, uint>((value) => (uint)value);
RegisterUnsafe<int, long>((value) => value);
RegisterUnsafe<int, ulong>((value) => (ulong)value);
RegisterUnsafe<int, double>((value) => value);
RegisterUnsafe<int, float>((value) => checked((float)value));
RegisterUnsafe<int, FdbTupleAlias>((value) => (FdbTupleAlias)value);
RegisterUnsafe<uint, Slice>((value) => Slice.FromUInt64(value));
RegisterUnsafe<uint, byte[]>((value) => Slice.FromUInt64(value).GetBytes());
RegisterUnsafe<uint, string>((value) => value.ToString(CultureInfo.InvariantCulture)); //TODO: string table!
RegisterUnsafe<uint, bool>((value) => value != 0);
RegisterUnsafe<uint, sbyte>((value) => checked((sbyte)value));
RegisterUnsafe<uint, byte>((value) => checked((byte)value));
RegisterUnsafe<uint, short>((value) => checked((short)value));
RegisterUnsafe<uint, ushort>((value) => checked((ushort)value));
RegisterUnsafe<uint, int>((value) => (int)value);
RegisterUnsafe<uint, long>((value) => value);
RegisterUnsafe<uint, ulong>((value) => value);
RegisterUnsafe<uint, double>((value) => value);
RegisterUnsafe<uint, float>((value) => checked((float)value));
RegisterUnsafe<long, Slice>((value) => Slice.FromInt64(value));
RegisterUnsafe<long, byte[]>((value) => Slice.FromInt64(value).GetBytes());
RegisterUnsafe<long, string>((value) => value.ToString(CultureInfo.InvariantCulture)); //TODO: string table!
RegisterUnsafe<long, bool>((value) => value != 0);
RegisterUnsafe<long, sbyte>((value) => checked((sbyte)value));
RegisterUnsafe<long, byte>((value) => checked((byte)value));
RegisterUnsafe<long, short>((value) => checked((short)value));
RegisterUnsafe<long, ushort>((value) => checked((ushort)value));
RegisterUnsafe<long, int>((value) => checked((int)value));
RegisterUnsafe<long, uint>((value) => (uint)value);
RegisterUnsafe<long, ulong>((value) => (ulong)value);
RegisterUnsafe<long, double>((value) => checked((double)value));
RegisterUnsafe<long, float>((value) => checked((float)value));
RegisterUnsafe<long, TimeSpan>((value) => TimeSpan.FromTicks(value));
RegisterUnsafe<long, Uuid64>((value) => new Uuid64(value));
RegisterUnsafe<long, System.Net.IPAddress>((value) => new System.Net.IPAddress(value));
RegisterUnsafe<ulong, Slice>((value) => Slice.FromUInt64(value));
RegisterUnsafe<ulong, byte[]>((value) => Slice.FromUInt64(value).GetBytes());
RegisterUnsafe<ulong, string>((value) => value.ToString(CultureInfo.InvariantCulture)); //TODO: string table!
RegisterUnsafe<ulong, bool>((value) => value != 0);
RegisterUnsafe<ulong, sbyte>((value) => checked((sbyte)value));
RegisterUnsafe<ulong, byte>((value) => checked((byte)value));
RegisterUnsafe<ulong, short>((value) => checked((short)value));
RegisterUnsafe<ulong, ushort>((value) => checked((ushort)value));
RegisterUnsafe<ulong, int>((value) => checked((int)value));
RegisterUnsafe<ulong, uint>((value) => checked((uint)value));
RegisterUnsafe<ulong, long>((value) => checked((long)value));
RegisterUnsafe<ulong, double>((value) => checked((double)value));
RegisterUnsafe<ulong, float>((value) => checked((float)value));
RegisterUnsafe<ulong, Uuid64>((value) => new Uuid64(value));
RegisterUnsafe<ulong, TimeSpan>((value) => TimeSpan.FromTicks(checked((long)value)));
RegisterUnsafe<short, Slice>((value) => Slice.FromInt32(value));
RegisterUnsafe<short, byte[]>((value) => Slice.FromInt32(value).GetBytes());
RegisterUnsafe<short, string>((value) => value.ToString(CultureInfo.InvariantCulture)); //TODO: string table!
RegisterUnsafe<short, bool>((value) => value != 0);
RegisterUnsafe<short, sbyte>((value) => checked((sbyte)value));
RegisterUnsafe<short, byte>((value) => checked((byte)value));
RegisterUnsafe<short, ushort>((value) => checked((ushort)value));
RegisterUnsafe<short, int>((value) => value);
RegisterUnsafe<short, uint>((value) => checked((uint)value));
RegisterUnsafe<short, long>((value) => value);
RegisterUnsafe<short, ulong>((value) => checked((ulong)value));
RegisterUnsafe<short, double>((value) => value);
RegisterUnsafe<short, float>((value) => value);
RegisterUnsafe<short, FdbTupleAlias>((value) => (FdbTupleAlias)value);
RegisterUnsafe<ushort, Slice>((value) => Slice.FromUInt64(value));
RegisterUnsafe<ushort, byte[]>((value) => Slice.FromUInt64(value).GetBytes());
RegisterUnsafe<ushort, string>((value) => value.ToString(CultureInfo.InvariantCulture)); //TODO: string table!
RegisterUnsafe<ushort, bool>((value) => value != 0);
RegisterUnsafe<ushort, byte>((value) => checked((byte)value));
RegisterUnsafe<ushort, sbyte>((value) => checked((sbyte)value));
RegisterUnsafe<ushort, short>((value) => checked((short)value));
RegisterUnsafe<ushort, int>((value) => value);
RegisterUnsafe<ushort, uint>((value) => value);
RegisterUnsafe<ushort, long>((value) => value);
RegisterUnsafe<ushort, ulong>((value) => value);
RegisterUnsafe<ushort, double>((value) => value);
RegisterUnsafe<ushort, float>((value) => value);
RegisterUnsafe<byte, Slice>((value) => Slice.FromInt32(value));
RegisterUnsafe<byte, byte[]>((value) => Slice.FromInt32(value).GetBytes());
RegisterUnsafe<byte, string>((value) => value.ToString(CultureInfo.InvariantCulture)); //TODO: string table!
RegisterUnsafe<byte, bool>((value) => value != 0);
RegisterUnsafe<byte, sbyte>((value) => checked((sbyte)value));
RegisterUnsafe<byte, short>((value) => value);
RegisterUnsafe<byte, ushort>((value) => value);
RegisterUnsafe<byte, int>((value) => value);
RegisterUnsafe<byte, uint>((value) => value);
RegisterUnsafe<byte, long>((value) => value);
RegisterUnsafe<byte, ulong>((value) => value);
RegisterUnsafe<byte, double>((value) => value);
RegisterUnsafe<byte, float>((value) => value);
RegisterUnsafe<byte, FdbTupleAlias>((value) => (FdbTupleAlias)value);
RegisterUnsafe<sbyte, Slice>((value) => Slice.FromInt64(value));
RegisterUnsafe<sbyte, byte[]>((value) => Slice.FromInt64(value).GetBytes());
RegisterUnsafe<sbyte, string>((value) => value.ToString(CultureInfo.InvariantCulture)); //TODO: string table!
RegisterUnsafe<sbyte, bool>((value) => value != 0);
RegisterUnsafe<sbyte, byte>((value) => checked((byte)value));
RegisterUnsafe<sbyte, short>((value) => value);
RegisterUnsafe<sbyte, ushort>((value) => checked((ushort)value));
RegisterUnsafe<sbyte, int>((value) => value);
RegisterUnsafe<sbyte, uint>((value) => checked((uint)value));
RegisterUnsafe<sbyte, long>((value) => value);
RegisterUnsafe<sbyte, ulong>((value) => checked((ulong)value));
RegisterUnsafe<sbyte, double>((value) => value);
RegisterUnsafe<sbyte, float>((value) => value);
RegisterUnsafe<float, Slice>((value) => Slice.FromSingle(value));
RegisterUnsafe<float, byte[]>((value) => Slice.FromSingle(value).GetBytes());
RegisterUnsafe<float, string>((value) => value.ToString("R", CultureInfo.InvariantCulture));
RegisterUnsafe<float, bool>((value) => !(value == 0f || float.IsNaN(value)));
RegisterUnsafe<float, sbyte>((value) => checked((sbyte)value));
RegisterUnsafe<float, byte>((value) => checked((byte)value));
RegisterUnsafe<float, short>((value) => checked((short)value));
RegisterUnsafe<float, ushort>((value) => checked((ushort)value));
RegisterUnsafe<float, int>((value) => checked((int)value));
RegisterUnsafe<float, uint>((value) => (uint)value);
RegisterUnsafe<float, long>((value) => checked((long)value));
RegisterUnsafe<float, ulong>((value) => (ulong)value);
RegisterUnsafe<float, double>((value) => value);
RegisterUnsafe<double, Slice>((value) => Slice.FromDouble(value));
RegisterUnsafe<double, byte[]>((value) => Slice.FromDouble(value).GetBytes());
RegisterUnsafe<double, string>((value) => value.ToString("R", CultureInfo.InvariantCulture));
RegisterUnsafe<double, bool>((value) => !(value == 0d || double.IsNaN(value)));
RegisterUnsafe<double, sbyte>((value) => checked((sbyte)value));
RegisterUnsafe<double, byte>((value) => checked((byte)value));
RegisterUnsafe<double, short>((value) => checked((short)value));
RegisterUnsafe<double, ushort>((value) => checked((ushort)value));
RegisterUnsafe<double, int>((value) => checked((int)value));
RegisterUnsafe<double, uint>((value) => (uint)value);
RegisterUnsafe<double, long>((value) => checked((long)value));
RegisterUnsafe<double, ulong>((value) => (ulong)value);
RegisterUnsafe<double, float>((value) => checked((float)value));
RegisterUnsafe<string, Slice>((value) => Slice.FromString(value));
RegisterUnsafe<string, byte[]>((value) => Slice.FromString(value).GetBytes());
RegisterUnsafe<string, bool>((value) => !string.IsNullOrEmpty(value));
RegisterUnsafe<string, sbyte>((value) => string.IsNullOrEmpty(value) ? default(sbyte) : SByte.Parse(value, CultureInfo.InvariantCulture));
RegisterUnsafe<string, byte>((value) => string.IsNullOrEmpty(value) ? default(byte) : Byte.Parse(value, CultureInfo.InvariantCulture));
RegisterUnsafe<string, short>((value) => string.IsNullOrEmpty(value) ? default(short) : Int16.Parse(value, CultureInfo.InvariantCulture));
RegisterUnsafe<string, ushort>((value) => string.IsNullOrEmpty(value) ? default(ushort) : UInt16.Parse(value, CultureInfo.InvariantCulture));
RegisterUnsafe<string, int>((value) => string.IsNullOrEmpty(value) ? default(int) : Int32.Parse(value, CultureInfo.InvariantCulture));
RegisterUnsafe<string, uint>((value) => string.IsNullOrEmpty(value) ? default(uint) : UInt32.Parse(value, CultureInfo.InvariantCulture));
RegisterUnsafe<string, long>((value) => string.IsNullOrEmpty(value) ? default(long) : Int64.Parse(value, CultureInfo.InvariantCulture));
RegisterUnsafe<string, ulong>((value) => string.IsNullOrEmpty(value) ? default(ulong) : UInt64.Parse(value, CultureInfo.InvariantCulture));
RegisterUnsafe<string, float>((value) => string.IsNullOrEmpty(value) ? default(float) : Single.Parse(value, NumberStyles.Float, CultureInfo.InvariantCulture));
RegisterUnsafe<string, double>((value) => string.IsNullOrEmpty(value) ? default(double) : Double.Parse(value, NumberStyles.Float, CultureInfo.InvariantCulture));
RegisterUnsafe<string, Guid>((value) => string.IsNullOrEmpty(value) ? default(Guid) : Guid.Parse(value));
RegisterUnsafe<string, Uuid128>((value) => string.IsNullOrEmpty(value) ? default(Uuid128) : Uuid128.Parse(value));
RegisterUnsafe<string, Uuid64>((value) => string.IsNullOrEmpty(value) ? default(Uuid64) : Uuid64.Parse(value));
RegisterUnsafe<string, System.Net.IPAddress>((value) => string.IsNullOrEmpty(value) ? default(System.Net.IPAddress) : System.Net.IPAddress.Parse(value));
RegisterUnsafe<byte[], Slice>((value) => Slice.Create(value));
RegisterUnsafe<byte[], string>((value) => value == null ? default(string) : value.Length == 0 ? String.Empty : System.Convert.ToBase64String(value));
RegisterUnsafe<byte[], bool>((value) => value != null && value.Length > 0);
RegisterUnsafe<byte[], sbyte>((value) => value == null ? default(sbyte) : Slice.Create(value).ToSByte());
RegisterUnsafe<byte[], byte>((value) => value == null ? default(byte) : Slice.Create(value).ToByte());
RegisterUnsafe<byte[], short>((value) => value == null ? default(short) : Slice.Create(value).ToInt16());
RegisterUnsafe<byte[], ushort>((value) => value == null ? default(ushort) : Slice.Create(value).ToUInt16());
RegisterUnsafe<byte[], int>((value) => value == null ? 0 : Slice.Create(value).ToInt32());
RegisterUnsafe<byte[], uint>((value) => value == null ? 0U : Slice.Create(value).ToUInt32());
RegisterUnsafe<byte[], long>((value) => value == null ? 0L : Slice.Create(value).ToInt64());
RegisterUnsafe<byte[], ulong>((value) => value == null ? 0UL : Slice.Create(value).ToUInt64());
RegisterUnsafe<byte[], Guid>((value) => value == null || value.Length == 0 ? default(Guid) : new Uuid128(value).ToGuid());
RegisterUnsafe<byte[], Uuid128>((value) => value == null || value.Length == 0 ? default(Uuid128) : new Uuid128(value));
RegisterUnsafe<byte[], Uuid64>((value) => value == null || value.Length == 0 ? default(Uuid64) : new Uuid64(value));
RegisterUnsafe<byte[], TimeSpan>((value) => value == null ? TimeSpan.Zero : TimeSpan.FromTicks(Slice.Create(value).ToInt64()));
RegisterUnsafe<byte[], System.Net.IPAddress>((value) => value == null || value.Length == 0 ? default(System.Net.IPAddress) : new System.Net.IPAddress(value));
RegisterUnsafe<Guid, Slice>((value) => Slice.FromGuid(value));
RegisterUnsafe<Guid, byte[]>((value) => Slice.FromGuid(value).GetBytes());
RegisterUnsafe<Guid, string>((value) => value.ToString("D", null));
RegisterUnsafe<Guid, Uuid128>((value) => new Uuid128(value));
RegisterUnsafe<Guid, bool>((value) => value != Guid.Empty);
RegisterUnsafe<Guid, System.Net.IPAddress>((value) => new System.Net.IPAddress(new Uuid128(value).ToByteArray()));
RegisterUnsafe<Uuid128, Slice>((value) => value.ToSlice());
RegisterUnsafe<Uuid128, byte[]>((value) => value.ToByteArray());
RegisterUnsafe<Uuid128, string>((value) => value.ToString("D", null));
RegisterUnsafe<Uuid128, Guid>((value) => value.ToGuid());
RegisterUnsafe<Uuid128, bool>((value) => value != Uuid128.Empty);
RegisterUnsafe<Guid, System.Net.IPAddress>((value) => new System.Net.IPAddress(value.ToByteArray()));
RegisterUnsafe<Uuid64, Slice>((value) => value.ToSlice());
RegisterUnsafe<Uuid64, byte[]>((value) => value.ToByteArray());
RegisterUnsafe<Uuid64, string>((value) => value.ToString("D", null));
RegisterUnsafe<Uuid64, long>((value) => value.ToInt64());
RegisterUnsafe<Uuid64, ulong>((value) => value.ToUInt64());
RegisterUnsafe<Uuid64, bool>((value) => value.ToInt64() != 0L);
RegisterUnsafe<TimeSpan, Slice>((value) => Slice.FromInt64(value.Ticks));
RegisterUnsafe<TimeSpan, byte[]>((value) => Slice.FromInt64(value.Ticks).GetBytes());
RegisterUnsafe<TimeSpan, long>((value) => value.Ticks);
RegisterUnsafe<TimeSpan, ulong>((value) => checked((ulong)value.Ticks));
RegisterUnsafe<TimeSpan, double>((value) => value.TotalSeconds);
RegisterUnsafe<TimeSpan, bool>((value) => value == TimeSpan.Zero);
RegisterUnsafe<System.Net.IPAddress, Slice>((value) => value != null ? Slice.Create(value.GetAddressBytes()) : Slice.Nil);
RegisterUnsafe<System.Net.IPAddress, byte[]>((value) => value != null ? value.GetAddressBytes() : null);
RegisterUnsafe<System.Net.IPAddress, string>((value) => value != null ? value.ToString() : null);
RegisterUnsafe<FdbTupleAlias, byte>((value) => (byte)value);
RegisterUnsafe<FdbTupleAlias, int>((value) => (int)value);
RegisterUnsafe<FdbTupleAlias, Slice>((value) => Slice.FromByte((byte)value));
//REVIEW: this should go in the Tuples layer !
RegisterUnsafe<Slice, byte[]>((value) => value.GetBytes());
RegisterUnsafe<Slice, string>((value) => value.ToUnicode());
RegisterUnsafe<Slice, bool>((value) => value.ToBool());
RegisterUnsafe<Slice, sbyte>((value) => value.ToSByte());
RegisterUnsafe<Slice, byte>((value) => value.ToByte());
RegisterUnsafe<Slice, short>((value) => value.ToInt16());
RegisterUnsafe<Slice, ushort>((value) => value.ToUInt16());
RegisterUnsafe<Slice, int>((value) => value.ToInt32());
RegisterUnsafe<Slice, uint>((value) => value.ToUInt32());
RegisterUnsafe<Slice, long>((value) => value.ToInt64());
RegisterUnsafe<Slice, ulong>((value) => value.ToUInt64());
RegisterUnsafe<Slice, Guid>((value) => value.ToGuid());
RegisterUnsafe<Slice, Uuid128>((value) => value.ToUuid128());
RegisterUnsafe<Slice, Uuid64>((value) => value.ToUuid64());
RegisterUnsafe<Slice, TimeSpan>((value) => TimeSpan.FromTicks(value.ToInt64()));
RegisterUnsafe<Slice, FdbTupleAlias>((value) => (FdbTupleAlias)value.ToByte());
RegisterUnsafe<Slice, System.Net.IPAddress>((value) => !value.IsNullOrEmpty ? new System.Net.IPAddress(value.GetBytes()) : null);
}
19
Source : FdbTuplePackers.cs
with MIT License
from abdullin
with MIT License
from abdullin
[CanBeNull]
public static System.Net.IPAddress DeserializeIPAddress(Slice slice)
{
if (slice.IsNullOrEmpty) return null;
int type = slice[0];
switch (type)
{
case FdbTupleTypes.Bytes:
{
return new System.Net.IPAddress(FdbTupleParser.ParseBytes(slice).GetBytes());
}
case FdbTupleTypes.Utf8:
{
return System.Net.IPAddress.Parse(FdbTupleParser.ParseUnicode(slice));
}
case FdbTupleTypes.Uuid128:
{ // could be an IPv6 encoded as a 128-bits UUID
return new System.Net.IPAddress(slice.GetBytes());
}
}
if (type >= FdbTupleTypes.IntPos1 && type <= FdbTupleTypes.IntPos4)
{ // could be an IPv4 encoded as a 32-bit unsigned integer
var value = FdbTupleParser.ParseInt64(type, slice);
Contract.replacedert(value >= 0 && value <= uint.MaxValue);
return new System.Net.IPAddress(value);
}
throw new FormatException(String.Format("Cannot convert tuple segment of type 0x{0:X} into System.Net.IPAddress", type));
}
19
Source : AccountTests.cs
with GNU Affero General Public License v3.0
from ACEmulator
with GNU Affero General Public License v3.0
from ACEmulator
[TestMethod]
public void CreateAccount_GetAccountByName_ReturnsAccount()
{
var newAccount = authDb.CreateAccount("testaccount1", "testpreplacedword1", AccessLevel.Player, IPAddress.Parse("127.0.0.1"));
var results = authDb.GetAccountByName(newAccount.AccountName);
replacedert.IsNotNull(results);
replacedert.IsTrue(results.AccessLevel == (uint)AccessLevel.Player);
}
19
Source : AccountCommands.cs
with GNU Affero General Public License v3.0
from ACEmulator
with GNU Affero General Public License v3.0
from ACEmulator
[CommandHandler("accountcreate", AccessLevel.Admin, CommandHandlerFlag.None, 2,
"Creates a new account.",
"username preplacedword (accesslevel)\n" +
"accesslevel can be a number or enum name\n" +
"0 = Player | 1 = Advocate | 2 = Sentinel | 3 = Envoy | 4 = Developer | 5 = Admin")]
public static void HandleAccountCreate(Session session, params string[] parameters)
{
AccessLevel defaultAccessLevel = (AccessLevel)Common.ConfigManager.Config.Server.Accounts.DefaultAccessLevel;
if (!Enum.IsDefined(typeof(AccessLevel), defaultAccessLevel))
defaultAccessLevel = AccessLevel.Player;
var accessLevel = defaultAccessLevel;
if (parameters.Length > 2)
{
if (Enum.TryParse(parameters[2], true, out accessLevel))
{
if (!Enum.IsDefined(typeof(AccessLevel), accessLevel))
accessLevel = defaultAccessLevel;
}
}
string articleAorAN = "a";
if (accessLevel == AccessLevel.Advocate || accessLevel == AccessLevel.Admin || accessLevel == AccessLevel.Envoy)
articleAorAN = "an";
string message = "";
var accountExists = DatabaseManager.Authentication.GetAccountByName(parameters[0]);
if (accountExists != null)
{
message= "Account already exists. Try a new name.";
}
else
{
try
{
var account = DatabaseManager.Authentication.CreateAccount(parameters[0].ToLower(), parameters[1], accessLevel, IPAddress.Parse("127.0.0.1"));
if (DatabaseManager.AutoPromoteNextAccountToAdmin && accessLevel == AccessLevel.Admin)
DatabaseManager.AutoPromoteNextAccountToAdmin = false;
message = ("Account successfully created for " + account.AccountName + " (" + account.AccountId + ") with access rights as " + articleAorAN + " " + Enum.GetName(typeof(AccessLevel), accessLevel) + ".");
}
catch
{
message = "Account already exists. Try a new name.";
}
}
CommandHandlerHelper.WriteOutputInfo(session, message, ChatMessageType.WorldBroadcast);
}
19
Source : SocketManager.cs
with GNU Affero General Public License v3.0
from ACEmulator
with GNU Affero General Public License v3.0
from ACEmulator
public static void Initialize()
{
var hosts = new List<IPAddress>();
try
{
var splits = ConfigManager.Config.Server.Network.Host.Split(",");
foreach (var split in splits)
hosts.Add(IPAddress.Parse(split));
}
catch (Exception ex)
{
log.Error($"Unable to use {ConfigManager.Config.Server.Network.Host} as host due to: {ex}");
log.Error("Using IPAddress.Any as host instead.");
hosts.Clear();
hosts.Add(IPAddress.Any);
}
listeners = new ConnectionListener[hosts.Count * 2];
for (int i = 0; i < hosts.Count; i++)
{
listeners[(i * 2) + 0] = new ConnectionListener(hosts[i], ConfigManager.Config.Server.Network.Port);
log.Info($"Binding ConnectionListener to {hosts[i]}:{ConfigManager.Config.Server.Network.Port}");
listeners[(i * 2) + 1] = new ConnectionListener(hosts[i], ConfigManager.Config.Server.Network.Port + 1);
log.Info($"Binding ConnectionListener to {hosts[i]}:{ConfigManager.Config.Server.Network.Port + 1}");
listeners[(i * 2) + 0].Start();
listeners[(i * 2) + 1].Start();
}
}
19
Source : JobNotification.cs
with MIT License
from actions
with MIT License
from actions
private void ConnectMonitor(string monitorSocketAddress)
{
int port = -1;
if (!_isMonitorConfigured && !String.IsNullOrEmpty(monitorSocketAddress))
{
try
{
string[] splitAddress = monitorSocketAddress.Split(':');
if (splitAddress.Length != 2)
{
Trace.Error("Invalid socket address {0}. Unable to connect to monitor.", monitorSocketAddress);
return;
}
IPAddress address;
try
{
address = IPAddress.Parse(splitAddress[0]);
}
catch (FormatException e)
{
Trace.Error("Invalid socket IP address {0}. Unable to connect to monitor.", splitAddress[0]);
Trace.Error(e);
return;
}
Int32.TryParse(splitAddress[1], out port);
if (port < IPEndPoint.MinPort || port > IPEndPoint.MaxPort)
{
Trace.Error("Invalid TCP socket port {0}. Unable to connect to monitor.", splitAddress[1]);
return;
}
Trace.Verbose("Trying to connect to monitor at port {0}", port);
_monitorSocket = new Socket(SocketType.Stream, ProtocolType.Tcp);
_monitorSocket.Connect(address, port);
Trace.Info("Connection successful to local port {0}", port);
_isMonitorConfigured = true;
}
catch (Exception e)
{
Trace.Error("Connection to monitor port {0} failed!", port);
Trace.Error(e);
}
}
}
19
Source : BankId_Authentication_Tests.cs
with MIT License
from ActiveLogin
with MIT License
from ActiveLogin
private static Action<IApplicationBuilder> DefaultAppConfiguration(Func<HttpContext, Task> testpath)
{
return app =>
{
app.UseMiddleware<FakeRemoteIpAddressMiddleware>(IPAddress.Parse("192.0.2.1"));
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapDefaultControllerRoute();
});
app.Use(async (context, next) =>
{
await testpath(context);
await next();
});
app.Run(context => context.Response.WriteAsync(""));
};
}
19
Source : AppManager.cs
with MIT License
from admaiorastudio
with MIT License
from admaiorastudio
private async Task ConnectAsync()
{
if (_isConnected)
return;
// Emulators loopback addresses
IPAddress[] loopbackAddresses = new[]
{
IPAddress.Parse("127.0.0.1"),
IPAddress.Parse("10.0.2.2"),
IPAddress.Parse("10.0.3.2"),
IPAddress.Parse("169.254.80.80")
};
// Check if we are an emulator instance
List<Task<string>> waitTasks = new List<Task<string>>();
CancellationTokenSource cts = new CancellationTokenSource();
// Look for server using localhost (an emulator device)
foreach (var ipAddress in loopbackAddresses.Take(1))
{
waitTasks.Add(Task.Run<string>(
async () =>
{
try
{
bool isPortOpen = TryPing(ipAddress.ToString(), 5001, 300);
if (!isPortOpen)
return null;
var connection = new HubConnectionBuilder()
.WithUrl($"http://{ipAddress.ToString()}:5001/hub")
.Build();
await connection.StartAsync(cts.Token);
if (cts.IsCancellationRequested)
return null;
_useLocalHost = true;
_hubConnection = connection;
cts.Cancel();
return ipAddress.ToString();
}
catch (Exception ex)
{
return null;
}
}, cts.Token));
}
// Look for server using broadcast (a real device)
waitTasks.Add(Task.Run<string>(
async () =>
{
// Discover the server
using (UdpClient client = new UdpClient())
{
client.EnableBroadcast = true;
byte[] requestData = Encoding.ASCII.GetBytes($"AreYouTheServer?");
Task<int> sendTask = client.SendAsync(requestData, requestData.Length, new IPEndPoint(IPAddress.Broadcast, 5002));
await Task.WhenAny(new[] { sendTask, Task.Delay(300) });
if (sendTask.IsCompleted)
{
if (cts.IsCancellationRequested)
return null;
Task<UdpReceiveResult> receiveTask = client.ReceiveAsync();
await Task.WhenAny(new[] { receiveTask, Task.Delay(300) });
if (receiveTask.IsCompleted)
{
if (cts.IsCancellationRequested)
return null;
UdpReceiveResult serverResponseData = receiveTask.Result;
string serverResponse = Encoding.ASCII.GetString(serverResponseData.Buffer);
if (serverResponse == "YesIamTheServer!")
{
string ipAddress = serverResponseData.RemoteEndPoint.Address.ToString();
_useLocalHost = false;
_hubConnection = null;
cts.Cancel();
return ipAddress.ToString();
}
}
}
client.Close();
}
return null;
}));
// Timeout task
waitTasks.Add(Task.Run<string>(
async () =>
{
try
{
await Task.Delay(5000, cts.Token);
cts.Cancel();
return null;
}
catch
{
return null;
}
}));
try
{
string ipAddress = await WaitForAnyGetHostIpTaskAsync(waitTasks);
if (ipAddress != null)
{
if (_hubConnection == null)
{
string port = _useLocalHost ? "5001" : "5002";
_hubConnection = new HubConnectionBuilder()
.WithUrl($"http://{ipAddress.ToString()}:{port}/hub")
.Build();
await _hubConnection.StartAsync();
}
_isConnected = true;
_serverAddress = ipAddress;
_hubConnection.Closed +=
async (error) =>
{
System.Diagnostics.Debug.WriteLine("Connection with RealXaml has been lost.");
while(_hubConnection.State == HubConnectionState.Disconnected)
{
bool isPortOpen = TryPing(ipAddress.ToString(), 5001, 300);
if (isPortOpen)
{
System.Diagnostics.Debug.WriteLine("Trying to reconnect again...");
await _hubConnection.StartAsync();
if (_hubConnection.State == HubConnectionState.Connected)
{
await Task.Delay(300);
await _hubConnection.SendAsync("NotifyIde", "Connection was lost. Here I'am again.");
System.Diagnostics.Debug.WriteLine($"Successfully restored lost to the RealXaml server.");
break;
}
}
System.Diagnostics.Debug.WriteLine("Unable to connect. Retrying in 5secs.");
await Task.Delay(5000);
}
};
_hubConnection.On<string, byte[], bool>("ReloadXaml",
async (pageId, data, refresh) => await WhenReloadXaml(pageId, data, refresh));
_hubConnection.On<string, byte[]>("Reloadreplacedembly",
async (replacedemblyName, data) => await WhenReloadreplacedembly(replacedemblyName, data));
string clientId = $"RXID-{DateTime.Now.Ticks}";
await _hubConnection.SendAsync("RegisterClient", clientId);
System.Diagnostics.Debug.WriteLine($"Successfully connected to the RealXaml server.");
System.Diagnostics.Debug.WriteLine($"Your client ID is {clientId}");
return;
}
}
catch(Exception ex)
{
System.Diagnostics.Debug.WriteLine("Error while trying to connect to the RealXaml server.");
System.Diagnostics.Debug.WriteLine(ex);
}
}
19
Source : Program.cs
with GNU General Public License v3.0
from AdvancedHacker101
with GNU General Public License v3.0
from AdvancedHacker101
public void start()
{
if (ep == null) ep = new IPEndPoint(IPAddress.Parse("8.8.8.8"), 53);
Console.WriteLine("Endpoint Created!");
client = new UdpClient();
client.Connect(ep);
Console.WriteLine("UDP Connected");
}
19
Source : UdpSocket.cs
with Apache License 2.0
from advancer68
with Apache License 2.0
from advancer68
public void Connect(string host, int port)
{
mSvrEndPoint = new IPEndPoint(IPAddress.Parse(host), port);
mUdpClient = new UdpClient(host, port);
UnityEngine.Debug.LogFormat("snd buff size:{0},rcv buff size:{1}", mUdpClient.Client.SendBufferSize, mUdpClient.Client.ReceiveBufferSize);
mUdpClient.Connect(mSvrEndPoint);
state = State.Connect;
//init_kcp((UInt32)new Random((int)DateTime.Now.Ticks).Next(1, Int32.MaxValue));
init_kcp(0);
if (rcvSync)
{
mUdpClient.BeginReceive(ReceiveCallback, this);
}
else
{
//ThreadPool.QueueUserWorkItem(new WaitCallback(process_rcv_queue));
}
ThreadPool.QueueUserWorkItem(new WaitCallback(process_kcpio_queue));
}
19
Source : Program.cs
with MIT License
from afxw
with MIT License
from afxw
public void TryConnect()
{
isConnected = false;
PrintDebug("Waiting for Server...");
while (!client.TcpClient.Connected)
{
try
{
client.Connect(IPAddress.Parse(ClientConfiguration.Host), ClientConfiguration.Port);
}
catch (Exception)
{
continue;
}
}
isConnected = true;
PrintDebug("Connected!");
}
19
Source : GAnalytics.cs
with GNU General Public License v3.0
from AgentRev
with GNU General Public License v3.0
from AgentRev
public static int GetUniqueID()
{
string commentForCodeLurkers = "This is to find the public IPv4 address of the client to use it as unique ID for replacedytics";
try
{
var client = new TimedWebClient();
var ipAddress = client.DownloadString(ipService);
ipAddress = Regex.Match(ipAddress, @"([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3})").Groups[1].Value;
return BitConverter.ToInt32(IPAddress.Parse(ipAddress).GetAddressBytes(), 0);
}
catch
{
Random rnd = new Random();
return rnd.Next(int.MinValue, int.MaxValue);
}
}
19
Source : DatabaseFixture.cs
with Apache License 2.0
from AkkaNetContrib
with Apache License 2.0
from AkkaNetContrib
private Task InitializeProjections(int httpPort)
{
var logger = new NoLogger();
var endpoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), httpPort);
var pm = new ProjectionsManager(logger, endpoint, TimeSpan.FromSeconds(2));
return Task.WhenAll(Tags.Select(async tag =>
{
var source = ReadTaggedProjectionSource(tag);
await pm.CreateContinuousAsync(tag, source, new UserCredentials("admin", "changeit"));
}));
}
19
Source : DockerSupport.cs
with Apache License 2.0
from akkadotnet
with Apache License 2.0
from akkadotnet
private IPEndPoint TemporaryTcpAddress(string hostName)
{
using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
var endpoint = new IPEndPoint(IPAddress.Parse(hostName), 0);
socket.Bind(endpoint);
return (IPEndPoint) socket.LocalEndPoint;
}
}
19
Source : CharacterManagementHandler.cs
with GNU General Public License v3.0
from AlanMorel
with GNU General Public License v3.0
from AlanMorel
public void HandleSelect(LoginSession session, PacketReader packet)
{
long characterId = packet.ReadLong();
packet.ReadShort(); // 01 00
Logger.Info($"Logging in to game with char id: {characterId}");
string ipAddress = Environment.GetEnvironmentVariable("IP");
int port = int.Parse(Environment.GetEnvironmentVariable("GAME_PORT"));
IPEndPoint endpoint = new IPEndPoint(IPAddress.Parse(ipAddress), port);
Player player = DatabaseManager.Characters.FindPlayerById(characterId);
if (player == default)
{
Logger.Error("Character not found!");
return;
}
player.ChannelId = 1;
player.InstanceId = 1;
AuthData authData = new AuthData
{
TokenA = LoginSession.GetToken(),
TokenB = LoginSession.GetToken(),
Player = player,
};
// Write AuthData to storage shared with GameServer
AuthStorage.SetData(session.AccountId, authData);
session.Send(MigrationPacket.LoginToGame(endpoint, authData));
}
19
Source : Player.cs
with GNU General Public License v3.0
from AlanMorel
with GNU General Public License v3.0
from AlanMorel
public void WarpGameToGame(int mapId, long instanceId, CoordF? coord = null, CoordF? rotation = null)
{
UpdateCoords(mapId, instanceId, coord, rotation);
string ipAddress = Environment.GetEnvironmentVariable("IP");
int port = int.Parse(Environment.GetEnvironmentVariable("GAME_PORT"));
IPEndPoint endpoint = new IPEndPoint(IPAddress.Parse(ipAddress), port);
AuthData authTokens = AuthStorage.GetData(AccountId);
authTokens.Player.IsChangingChannel = true;
DatabaseManager.Characters.Update(this);
Session.Send(MigrationPacket.GameToGame(endpoint, authTokens, this));
}
19
Source : NamedServerStream.cs
with MIT License
from alchemz
with MIT License
from alchemz
public void ListenForMessages(int port)
{
TcpListener server = null;
try
{
// Set the TcpListener on port 13000.
IPAddress localAddr = IPAddress.Parse("127.0.0.1");
// TcpListener server = new TcpListener(port);
server = new TcpListener(localAddr, port);
// Start listening for client requests.
server.Start();
// Buffer for reading data
Byte[] bytes = new Byte[256];
String data = null;
// Enter the listening loop.
while (true)
{
Debug.Log("Waiting for a connection... ");
// Perform a blocking call to accept requests.
// You could also user server.AcceptSocket() here.
using (TcpClient client = server.AcceptTcpClient())
{
Debug.Log("Connected!");
data = null;
// Get a stream object for reading and writing
NetworkStream stream = client.GetStream();
int i;
// Loop to receive all the data sent by the client.
while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
{
// Translate data bytes to a ASCII string.
data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
Debug.Log(String.Format("Received: {0}", data));
var viewModel = JsonUtility.FromJson<DataPointViewModel>(data);
lock (queueLock)
{
dataPointsQueue.Enqueue(viewModel);
}
// Process the data sent by the client.
data = data.ToUpper();
byte[] msg = System.Text.Encoding.ASCII.GetBytes(data);
// Send back a response.
stream.Write(msg, 0, msg.Length);
Debug.Log(String.Format("Sent: {0}", data));
}
}
}
}
catch (SocketException e)
{
Debug.LogError(String.Format("SocketException: {0}", e));
}
finally
{
// Stop listening for new clients.
server.Stop();
}
}
19
Source : TCPServerEnd.cs
with MIT License
from alchemz
with MIT License
from alchemz
public void ListenForMessage(int port)
{
TcpListener server = null;
try
{
// Set the TcpListener on port 13000.
IPAddress localAddr = IPAddress.Parse("127.0.0.1");
// TcpListener server = new TcpListener(port);
server = new TcpListener(localAddr, port);
// Start listening for client requests.
server.Start();
// Buffer for reading data
Byte[] bytes = new Byte[256];
String data = null;
// Enter the listening loop.
while (true)
{
Debug.Log("Waiting for a connection... ");
//Console.Write("Waiting for a connection... ");
// Perform a blocking call to accept requests.
// You could also user server.AcceptSocket() here.
TcpClient client = server.AcceptTcpClient();
Debug.Log("Connected!");
data = null;
// Get a stream object for reading and writing
NetworkStream stream = client.GetStream();
int i;
// Loop to receive all the data sent by the client.
while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
{
// Translate data bytes to a ASCII string.
data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
Debug.Log(String.Format("Received: {0}", data));
// Process the data sent by the client.
data = data.ToUpper();
byte[] msg = System.Text.Encoding.ASCII.GetBytes(data);
// Send back a response.
stream.Write(msg, 0, msg.Length);
Debug.Log(String.Format("Sent: {0}", data));
}
// Shutdown and end connection
client.Close();
}
}
catch (SocketException e)
{
Debug.LogError(String.Format("SocketException: {0}", e));
}
finally
{
// Stop listening for new clients.
server.Stop();
}
}
19
Source : TCPServerEnd.cs
with MIT License
from alchemz
with MIT License
from alchemz
public void ListenForMessages(int port)
{
TcpListener server = null;
try
{
// Set the TcpListener on port 13000.
IPAddress localAddr = IPAddress.Parse("127.0.0.1");
// TcpListener server = new TcpListener(port);
server = new TcpListener(localAddr, port);
// Start listening for client requests.
server.Start();
// Buffer for reading data
Byte[] bytes = new Byte[256];
String data = null;
// Enter the listening loop.
while (true)
{
Debug.Log("Waiting for a connection... ");
//Console.Write("Waiting for a connection... ");
// Perform a blocking call to accept requests.
// You could also user server.AcceptSocket() here.
TcpClient client = server.AcceptTcpClient();
Debug.Log("Connected!");
data = null;
// Get a stream object for reading and writing
NetworkStream stream = client.GetStream();
int i;
// Loop to receive all the data sent by the client.
while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
{
// Translate data bytes to a ASCII string.
data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
Debug.Log(String.Format("Received: {0}", data));
// var viewModel=new DataPointViewModel();
// viewModel.rightAscendsion = UnityEngine.Random.value;
// viewModel.declination= UnityEngine.Random.Range(-1f,1f);
// viewModel.color= Color.cyan;
var viewModel=JsonUtility.FromJson<DataPointViewModel>(data);
lock(queueLock)
{
dataPointsQueue.Enqueue(viewModel);
}
// Process the data sent by the client.
data = data.ToUpper();
byte[] msg = System.Text.Encoding.ASCII.GetBytes(data);
// Send back a response.
stream.Write(msg, 0, msg.Length);
Debug.Log(String.Format("Sent: {0}", data));
}
// Shutdown and end connection
client.Close();
}
}
catch (SocketException e)
{
Debug.LogError(String.Format("SocketException: {0}", e));
}
finally
{
// Stop listening for new clients.
server.Stop();
}
}
19
Source : KIp6Address.cs
with MIT License
from alethic
with MIT License
from alethic
public static KIp6Address Parse(ReadOnlySpan<char> text)
{
#if NETSTANDARD2_0
return new KIp6Address(IPAddress.Parse(text.ToString()));
#else
return new KIp6Address(IPAddress.Parse(text));
#endif
}
19
Source : KIp6Address.cs
with MIT License
from alethic
with MIT License
from alethic
public static KIp6Address Parse(string text)
{
return new KIp6Address(IPAddress.Parse(text));
}
19
Source : KIpEndpoint.cs
with MIT License
from alethic
with MIT License
from alethic
public static KIpEndpoint Parse(string value)
{
if (Uri.TryCreate(value, UriKind.Absolute, out Uri uri))
return new IPEndPoint(IPAddress.Parse(uri.Host), uri.Port < 0 ? 0 : uri.Port);
if (Uri.TryCreate($"tcp://{value}", UriKind.Absolute, out uri))
return new IPEndPoint(IPAddress.Parse(uri.Host), uri.Port < 0 ? 0 : uri.Port);
if (Uri.TryCreate($"tcp://[{value}]", UriKind.Absolute, out uri))
return new IPEndPoint(IPAddress.Parse(uri.Host), uri.Port < 0 ? 0 : uri.Port);
throw new FormatException("Failed to parse text to KIpEndpoint.");
}
19
Source : KIp4Address.cs
with MIT License
from alethic
with MIT License
from alethic
public static KIp4Address Parse(ReadOnlySpan<char> text)
{
#if NETSTANDARD2_0
return new KIp4Address(IPAddress.Parse(text.ToString()));
#else
return new KIp4Address(IPAddress.Parse(text));
#endif
}
19
Source : KIp4Address.cs
with MIT License
from alethic
with MIT License
from alethic
public static KIp4Address Parse(string text)
{
return new KIp4Address(IPAddress.Parse(text));
}
19
Source : App.cs
with MIT License
from alexanderdna
with MIT License
from alexanderdna
public ConnectPeersResult ConnectToPeers()
{
var peersFile = PathsProvider.Peers;
if (File.Exists(peersFile) is false)
{
Logger.Log(LogLevel.Warning, "Cannot find peers file.");
return ConnectPeersResult.NoPeersFile;
}
List<(IPAddress, int)> addresses = new();
try
{
var lines = File.ReadAllLines(peersFile);
for (int i = 0, c = lines.Length; i < c; ++i)
{
if (lines[i] == "") continue;
int posOfColon = lines[i].LastIndexOf(':');
if (posOfColon < 0)
{
Logger.Log(LogLevel.Warning, "Peers file seems to have invalid addresses.");
continue;
}
var host = IPAddress.Parse(lines[i].Substring(0, posOfColon));
var port = int.Parse(lines[i].Substring(posOfColon + 1));
if (port <= 0 || port > 65535)
{
Logger.Log(LogLevel.Warning, "Peers file seems to have invalid addresses.");
continue;
}
addresses.Add((host, port));
}
}
catch (Exception ex)
{
Logger.Log(LogLevel.Error, "Cannot connect to peers: " + ex.Message);
return ConnectPeersResult.Failure;
}
return Daemon.AcceptPeerList(addresses) ? ConnectPeersResult.Success : ConnectPeersResult.Failure;
}
19
Source : InfoMessage.cs
with MIT License
from alexandredenes
with MIT License
from alexandredenes
public static InfoMessage Parse(byte[] data)
{
JObject obj = JObject.Parse(Encoding.Default.GetString(data));
InfoMessage retVal = new InfoMessage();
JObject client = (JObject)obj["client"];
retVal.Client = new Dictionary<string, string>();
foreach(var x in client.Properties())
{
retVal.Client[x.Name] = (string)x.Value;
}
retVal.HostName = (string)obj["hostname"];
retVal.IPList = new IPAddress[obj["ipList"].Count()];
for(int x = 0; x < retVal.IPList.Length ;x++)
{
retVal.IPList[x] = IPAddress.Parse((string)obj["ipList"][x]);
}
retVal.Sender = (string)obj["sender"];
retVal.Services = new List<Service>();
foreach(JObject serviceElement in obj["services"])
{
Service serv = new Service();
serv.Actions = new Dictionary<string, Service.Action>();
foreach(var actionElement in ((JObject)serviceElement["actions"]).Properties())
{
Service.Action act = new Service.Action();
act.Cache = (bool)actionElement.Value["cache"];
act.Metric = new Service.Action.Metrics();
act.Metric.Meta = (bool)actionElement.Value["metrics"]["meta"];
act.Metric.Params = (bool)actionElement.Value["metrics"]["params"];
act.Name = actionElement.Name;
act.Params = new Dictionary<string, string>();
if (actionElement.Value["params"] != null)
{
foreach (var paramElement in ((JObject)actionElement.Value["params"]).Properties())
{
act.Params[paramElement.Name] = paramElement.Value.HasValues ? (string)paramElement.Value["type"] : (string)paramElement.Value;
}
}
serv.Actions[actionElement.Name] = act;
}
serv.Metadata = null;
serv.Name = (string)serviceElement["name"];
serv.Settings = null;
retVal.Services.Add(serv);
}
retVal.Ver = (string)obj["ver"];
return retVal;
}
19
Source : WksRecord.cs
with Apache License 2.0
from alexreinert
with Apache License 2.0
from alexreinert
internal override void ParseRecordData(DomainName origin, string[] stringRepresentation)
{
if (stringRepresentation.Length < 2)
throw new FormatException();
Address = IPAddress.Parse(stringRepresentation[0]);
Ports = stringRepresentation.Skip(1).Select(UInt16.Parse).ToList();
}
19
Source : AddressRecordBase.cs
with Apache License 2.0
from alexreinert
with Apache License 2.0
from alexreinert
internal override void ParseRecordData(DomainName origin, string[] stringRepresentation)
{
if (stringRepresentation.Length != 1)
throw new FormatException();
Address = IPAddress.Parse(stringRepresentation[0]);
}
See More Examples