Here are the examples of the csharp api System.Net.Sockets.TcpClient.Close() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
515 Examples
19
Source : CelesteNetTCPUDPConnection.cs
with MIT License
from 0x0ade
with MIT License
from 0x0ade
protected override void Dispose(bool disposing) {
base.Dispose(disposing);
try {
TCP.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 0);
TCP.Client.Disconnect(false);
} catch (Exception) {
}
try {
TCPReader.Dispose();
} catch (Exception) {
}
try {
TCPWriter.Dispose();
} catch (Exception) {
}
try {
TCPReaderStream.Dispose();
} catch (Exception) {
}
try {
TCPWriterStream.Dispose();
} catch (Exception) {
}
TCP.Close();
// UDP is a mess and the UdpClient can be shared.
if (ReadUDPThread != null) {
try {
UDP?.Client?.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 0);
} catch (Exception) {
}
UDP?.Close();
}
}
19
Source : ConnectClient.cs
with Apache License 2.0
from AantCoder
with Apache License 2.0
from AantCoder
public void Dispose()
{
ClientStream.Close();
Client.Close();
}
19
Source : OVRNetwork.cs
with MIT License
from absurd-joy
with MIT License
from absurd-joy
public void Broadcast(int payloadType, byte[] payload)
{
if (payload.Length > OVRNetwork.MaxPayloadLength)
{
Debug.LogWarningFormat("[OVRNetworkTcpServer] drop payload because it's too long: {0} bytes", payload.Length);
}
FrameHeader header = new FrameHeader();
header.protocolIdentifier = FrameHeaderMagicIdentifier;
header.payloadType = payloadType;
header.payloadLength = payload.Length;
byte[] headerBuffer = header.ToBytes();
byte[] dataBuffer = new byte[headerBuffer.Length + payload.Length];
headerBuffer.CopyTo(dataBuffer, 0);
payload.CopyTo(dataBuffer, headerBuffer.Length);
lock (clientsLock)
{
foreach (TcpClient client in clients)
{
if (client.Connected)
{
try
{
client.GetStream().BeginWrite(dataBuffer, 0, dataBuffer.Length, new AsyncCallback(DoWriteDataCallback), client.GetStream());
}
catch (SocketException e)
{
Debug.LogWarningFormat("[OVRNetworkTcpServer] close client because of socket error: {0}", e.Message);
client.GetStream().Close();
client.Close();
}
}
}
}
}
19
Source : OVRNetwork.cs
with MIT License
from absurd-joy
with MIT License
from absurd-joy
public void Disconnect()
{
if (tcpClient != null)
{
if (!readyReceiveDataEvent.WaitOne(5))
{
Debug.LogWarning("[OVRNetworkTcpClient] readyReceiveDataEvent not signaled. data receiving timeout?");
}
Debug.Log("[OVRNetworkTcpClient] close tcpClient");
try
{
tcpClient.GetStream().Close();
tcpClient.Close();
}
catch (Exception e)
{
Debug.LogWarning("[OVRNetworkTcpClient] " + e.Message);
}
tcpClient = null;
if (connectionStateChangedCallback != null)
{
connectionStateChangedCallback();
}
}
else
{
Debug.LogWarning("[OVRNetworkTcpClient] not connected");
}
}
19
Source : HotReloadConnectedClient.cs
with MIT License
from adospace
with MIT License
from adospace
public async void Run(CancellationToken cancellationToken)
{
var stream = _connectedClient.GetStream();
var factory = new WebSocketServerFactory();
try
{
var context = await factory.ReadHttpHeaderFromStreamAsync(stream, cancellationToken);
if (!context.IsWebSocketRequest)
{
_connectedClient.Close();
return;
}
var webSocket = await factory.AcceptWebSocketAsync(context, cancellationToken);
await Receive(webSocket, cancellationToken);
}
catch (OperationCanceledException)
{
}
}
19
Source : ReloadCommand.cs
with MIT License
from adospace
with MIT License
from adospace
private static async Task<bool> SendreplacedemblyToEmulatorAsync(string replacedemblyPath, IVsOutputWindowPane outputPane, bool debugging)
{
await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();
//ThreadHelper.ThrowIfNotOnUIThread();
//outputPane.OutputString($"Sending to emulator new replacedembly (debugging={debugging})...");
//outputPane.Activate(); // Brings this pane into view
var client = new TcpClient
{
ReceiveTimeout = 15000,
SendTimeout = 15000
};
try
{
await client.ConnectAsync(IPAddress.Loopback, 45820);
var replacedemblyRaw = await FileUtil.ReadAllFileAsync(replacedemblyPath);
var networkStream = client.GetStream();
var lengthBytes = BitConverter.GetBytes(replacedemblyRaw.Length);
await networkStream.WriteAsync(lengthBytes, 0, lengthBytes.Length);
await networkStream.WriteAsync(replacedemblyRaw, 0, replacedemblyRaw.Length);
await networkStream.FlushAsync();
var replacedemblySymbolStorePath = Path.Combine(Path.GetDirectoryName(replacedemblyPath), Path.GetFileNameWithoutExtension(replacedemblyPath) + ".pdb");
if (File.Exists(replacedemblySymbolStorePath) && debugging)
{
var replacedemblySynmbolStoreRaw = await FileUtil.ReadAllFileAsync(replacedemblySymbolStorePath);
lengthBytes = BitConverter.GetBytes(replacedemblySynmbolStoreRaw.Length);
await networkStream.WriteAsync(lengthBytes, 0, lengthBytes.Length);
await networkStream.WriteAsync(replacedemblySynmbolStoreRaw, 0, replacedemblySynmbolStoreRaw.Length);
await networkStream.FlushAsync();
}
else
{
lengthBytes = BitConverter.GetBytes(0);
await networkStream.WriteAsync(lengthBytes, 0, lengthBytes.Length);
await networkStream.FlushAsync();
}
var booleanBuffer = new byte[1];
if (await networkStream.ReadAsync(booleanBuffer, 0, 1) == 0)
throw new SocketException();
outputPane.OutputStringThreadSafe($"Sent new replacedembly ({replacedemblyRaw.Length} bytes) to emulator{Environment.NewLine}");
}
catch (Exception ex)
{
outputPane.OutputStringThreadSafe($@"
Unable to connect to ReactorUI Hot Reload module
Please ensure that:
1) Only one device is running among emulators and physical devices
2) Application is running either in debug or release mode
3) RxApplication call WithHotReload()
Socket exception: {ex.Message}
");
return false;
}
finally
{
client.Close();
}
return true;
}
19
Source : Program.cs
with MIT License
from adospace
with MIT License
from adospace
private static async Task<bool> SendreplacedemblyToEmulatorAsync(string replacedemblyPath, bool debugging = true)
{
//ThreadHelper.ThrowIfNotOnUIThread();
//outputPane.OutputString($"Sending to emulator new replacedembly (debugging={debugging})...");
//outputPane.Activate(); // Brings this pane into view
var client = new TcpClient
{
ReceiveTimeout = 15000,
SendTimeout = 15000
};
try
{
await client.ConnectAsync(IPAddress.Loopback, 45820);
var replacedemblyRaw = await FileUtil.ReadAllFileAsync(replacedemblyPath);
var networkStream = client.GetStream();
var lengthBytes = BitConverter.GetBytes(replacedemblyRaw.Length);
await networkStream.WriteAsync(lengthBytes, 0, lengthBytes.Length);
await networkStream.WriteAsync(replacedemblyRaw, 0, replacedemblyRaw.Length);
await networkStream.FlushAsync();
var replacedemblySymbolStorePath = Path.Combine(Path.GetDirectoryName(replacedemblyPath), Path.GetFileNameWithoutExtension(replacedemblyPath) + ".pdb");
if (File.Exists(replacedemblySymbolStorePath) && debugging)
{
var replacedemblySynmbolStoreRaw = await FileUtil.ReadAllFileAsync(replacedemblySymbolStorePath);
lengthBytes = BitConverter.GetBytes(replacedemblySynmbolStoreRaw.Length);
await networkStream.WriteAsync(lengthBytes, 0, lengthBytes.Length);
await networkStream.WriteAsync(replacedemblySynmbolStoreRaw, 0, replacedemblySynmbolStoreRaw.Length);
await networkStream.FlushAsync();
}
else
{
lengthBytes = BitConverter.GetBytes(0);
await networkStream.WriteAsync(lengthBytes, 0, lengthBytes.Length);
await networkStream.FlushAsync();
}
var booleanBuffer = new byte[1];
if (await networkStream.ReadAsync(booleanBuffer, 0, 1) == 0)
throw new SocketException();
Console.WriteLine($"Sent new replacedembly ({replacedemblyRaw.Length} bytes) to emulator{Environment.NewLine}");
}
catch (Exception ex)
{
Console.WriteLine($@"
Unable to connect to ReactorUI Hot Reload module
Please ensure that:
1) Only one device is running among emulators and physical devices
2) Application is running either in debug or release mode
3) RxApplication call WithHotReload()
Socket exception: {ex.Message}
");
return false;
}
finally
{
client.Close();
}
return true;
}
19
Source : HotReloadCommand.cs
with MIT License
from adospace
with MIT License
from adospace
private static async Task<bool> SendreplacedemblyToEmulatorAsync(ProgressMonitor progressMonitor, string replacedemblyPath, bool debugging)
{
var client = new TcpClient
{
ReceiveTimeout = 15000,
SendTimeout = 15000
};
try
{
await client.ConnectAsync(IPAddress.Loopback, 45820);
var replacedemblyRaw = await FileUtil.ReadAllFileAsync(replacedemblyPath);
var networkStream = client.GetStream();
var lengthBytes = BitConverter.GetBytes(replacedemblyRaw.Length);
await networkStream.WriteAsync(lengthBytes, 0, lengthBytes.Length);
await networkStream.WriteAsync(replacedemblyRaw, 0, replacedemblyRaw.Length);
await networkStream.FlushAsync();
var replacedemblySymbolStorePath = Path.Combine(Path.GetDirectoryName(replacedemblyPath), Path.GetFileNameWithoutExtension(replacedemblyPath) + ".pdb");
if (File.Exists(replacedemblySymbolStorePath) && debugging)
{
var replacedemblySynmbolStoreRaw = await FileUtil.ReadAllFileAsync(replacedemblySymbolStorePath);
lengthBytes = BitConverter.GetBytes(replacedemblySynmbolStoreRaw.Length);
await networkStream.WriteAsync(lengthBytes, 0, lengthBytes.Length);
await networkStream.WriteAsync(replacedemblySynmbolStoreRaw, 0, replacedemblySynmbolStoreRaw.Length);
await networkStream.FlushAsync();
}
else
{
lengthBytes = BitConverter.GetBytes(0);
await networkStream.WriteAsync(lengthBytes, 0, lengthBytes.Length);
await networkStream.FlushAsync();
}
var booleanBuffer = new byte[1];
if (await networkStream.ReadAsync(booleanBuffer, 0, 1) == 0)
throw new SocketException();
await progressMonitor.Log.WriteLineAsync($"Sent new replacedembly ({replacedemblyRaw.Length} bytes) to emulator");
}
catch (Exception ex)
{
await progressMonitor.ErrorLog.WriteLineAsync($@"
Unable to connect to ReactorUI Hot Reload module
Please ensure that:
1) Only one device is running among emulators and physical devices
2) Application is running either in debug or release mode
3) RxApplication call WithHotReload()
Socket exception: {ex.Message}");
return false;
}
finally
{
client.Close();
}
return true;
}
19
Source : TcpSocket.cs
with Apache License 2.0
from advancer68
with Apache License 2.0
from advancer68
public void Close()
{
client.Close();
}
19
Source : PeerDialer.cs
with MIT License
from AElfProject
with MIT License
from AElfProject
private async Task<X509Certificate> RetrieveServerCertificateAsync(DnsEndPoint remoteEndpoint)
{
Logger.LogDebug($"Starting certificate retrieval for {remoteEndpoint}.");
TcpClient client = null;
try
{
client = new TcpClient();
using (var cts = new CancellationTokenSource())
{
cts.CancelAfter(NetworkConstants.DefaultSslCertifFetchTimeout);
await client.ConnectAsync(remoteEndpoint.Host, remoteEndpoint.Port).WithCancellation(cts.Token);
using (var sslStream = new SslStream(client.GetStream(), true, (a, b, c, d) => true))
{
sslStream.ReadTimeout = NetworkConstants.DefaultSslCertifFetchTimeout;
sslStream.WriteTimeout = NetworkConstants.DefaultSslCertifFetchTimeout;
await sslStream.AuthenticateAsClientAsync(remoteEndpoint.Host).WithCancellation(cts.Token);
if (sslStream.RemoteCertificate == null)
{
Logger.LogDebug($"Certificate from {remoteEndpoint} is null");
return null;
}
Logger.LogDebug($"Retrieved certificate for {remoteEndpoint}.");
return FromX509Certificate(sslStream.RemoteCertificate);
}
}
}
catch (OperationCanceledException)
{
Logger.LogDebug($"Certificate retrieval connection timeout for {remoteEndpoint}.");
return null;
}
catch (Exception ex)
{
// swallow exception because it's currently not a hard requirement to
// upgrade the connection.
Logger.LogWarning(ex, $"Could not retrieve certificate from {remoteEndpoint}.");
}
finally
{
client?.Close();
}
return null;
}
19
Source : GuiderImpl.cs
with MIT License
from agalasso
with MIT License
from agalasso
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
if (sw != null)
{
sw.Close();
sw.Dispose();
sw = null;
}
if (sr != null)
{
sr.Close();
sr.Dispose();
sr = null;
}
if (tcpCli != null)
{
Debug.WriteLine("Disconnect from phd2");
tcpCli.Close();
tcpCli = null;
}
}
}
19
Source : GuiderImpl.cs
with MIT License
from agalasso
with MIT License
from agalasso
public void Terminate()
{
if (tcpCli != null)
tcpCli.Close();
}
19
Source : MainWindow.xaml.cs
with GNU Affero General Public License v3.0
from aianlinb
with GNU Affero General Public License v3.0
from aianlinb
private static string GetPatchServer(bool garena = false) {
var tcp = new TcpClient() { NoDelay = true };
tcp.Connect(Dns.GetHostAddresses(garena ? "login.tw.pathofexile.com" : "us.login.pathofexile.com"), garena ? 12999 : 12995);
var b = new byte[256];
tcp.Client.Send(new byte[] { 1, 4 });
tcp.Client.Receive(b);
tcp.Close();
return Encoding.Unicode.GetString(b, 35, b[34] * 2);
}
19
Source : TCPClientManager.cs
with MIT License
from akihiro0105
with MIT License
from akihiro0105
private void ConnectCallback(IAsyncResult ar)
{
var tcp = (TcpClient)ar.AsyncState;
tcp.EndConnect(ar);
tcp.ReceiveTimeout = 100;
stream = tcp.GetStream();
var bytes = new byte[tcp.ReceiveBufferSize];
while (isActiveThread)
{
try
{
var num = stream.Read(bytes, 0, bytes.Length);
if (num > 0)
{
var data = new byte[num];
Array.Copy(bytes, 0, data, 0, num);
if (ListenerMessageEvent != null) ListenerMessageEvent(Encoding.UTF8.GetString(data));
if (ListenerByteEvent != null) ListenerByteEvent(data);
}
}
catch (Exception e)
{
Console.Write(e);
}
}
stream.Close();
stream = null;
tcp.Close();
}
19
Source : TCPServerManager.cs
with MIT License
from akihiro0105
with MIT License
from akihiro0105
private void AcceptTcpClient(IAsyncResult ar)
{
var listener = (TcpListener)ar.AsyncState;
var tcpClient = listener.EndAcceptTcpClient(ar);
listener.BeginAcceptTcpClient(AcceptTcpClient, listener);
tcpClient.ReceiveTimeout = 100;
var stream = tcpClient.GetStream();
streamList.Add(stream);
var bytes = new byte[tcpClient.ReceiveBufferSize];
while (isActiveThread)
{
try
{
var num = stream.Read(bytes, 0, bytes.Length);
if (num > 0)
{
for (int i = 0; i < streamList.Count; i++)
{
if (streamList[i].CanWrite == true) streamList[i].Write(bytes, 0, num);
}
}
}
catch (Exception e)
{
Console.Write(e);
}
if (tcpClient.Client.Poll(1000, SelectMode.SelectRead) && tcpClient.Client.Available == 0) break;
}
stream.Close();
tcpClient.Close();
}
19
Source : Session.cs
with GNU General Public License v3.0
from AlanMorel
with GNU General Public License v3.0
from AlanMorel
private void CloseClient()
{
// Must close socket before network stream to prevent lingering
Client?.Client?.Close();
Client?.Close();
}
19
Source : EmulatorClientSocket.cs
with MIT License
from alanplotko
with MIT License
from alanplotko
private void phoneConnect() {
string addr = EmulatorConfig.Instance.PHONE_EVENT_MODE == EmulatorConfig.Mode.USB
? EmulatorConfig.USB_SERVER_IP : EmulatorConfig.WIFI_SERVER_IP;
try {
if (EmulatorConfig.Instance.PHONE_EVENT_MODE == EmulatorConfig.Mode.USB) {
setupPortForwarding(kPhoneEventPort);
}
TcpClient tcpClient = new TcpClient(addr, kPhoneEventPort);
connected = true;
ProcessConnection(tcpClient);
tcpClient.Close();
} finally {
connected = false;
}
}
19
Source : EmulatorClientSocket.cs
with MIT License
from alanplotko
with MIT License
from alanplotko
void OnDestroy() {
shouldStop = true;
if (phoneMirroringSocket != null) {
phoneMirroringSocket.Close ();
phoneMirroringSocket = null;
}
if (phoneEventThread != null) {
phoneEventThread.Join();
}
}
19
Source : TCPClientEnd.cs
with MIT License
from alchemz
with MIT License
from alchemz
void Connect(String server, int port, String message)
{
try
{
// Create a TcpClient.
// Note, for this client to work you need to have a TcpServer
// connected to the same address as specified by the server, port
// combination.
TcpClient client = new TcpClient(server, port);
// Translate the preplaceded message into ASCII and store it as a Byte array.
Byte[] data = System.Text.Encoding.ASCII.GetBytes(message);
// Get a client stream for reading and writing.
// Stream stream = client.GetStream();
NetworkStream stream = client.GetStream();
// Send the message to the connected TcpServer.
stream.Write(data, 0, data.Length);
Console.WriteLine("Sent: {0}", message);
// Receive the TcpServer.response.
// Buffer to store the response bytes.
data = new Byte[256];
// String to store the response ASCII representation.
String responseData = String.Empty;
// Read the first batch of the TcpServer response bytes.
Int32 bytes = stream.Read(data, 0, data.Length);
responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
Console.WriteLine("Received: {0}", responseData);
// Close everything.
stream.Close();
client.Close();
}
catch (ArgumentNullException e)
{
Console.WriteLine("ArgumentNullException: {0}", e);
}
catch (SocketException e)
{
Console.WriteLine("SocketException: {0}", e);
}
Console.WriteLine("\n Press Enter to continue...");
Console.Read();
}
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 : Client.cs
with MIT License
from alexanderdna
with MIT License
from alexanderdna
public async void StartAsync(CancellationToken cancellationToken)
{
try
{
await _context.RunLoop(cancellationToken);
}
catch (TaskCanceledException)
{
}
catch (System.IO.IOException)
{
_context.ShouldDisconnect = true;
}
finally
{
_client.Close();
}
}
19
Source : Context.cs
with MIT License
from alexanderdna
with MIT License
from alexanderdna
public void Close()
{
try
{
Client.GetStream().Close();
Client.Close();
}
catch (ObjectDisposedException)
{
}
}
19
Source : Server.cs
with MIT License
from alexanderdna
with MIT License
from alexanderdna
private async Task processClientAsync(TcpClient client, CancellationToken cancellationToken)
{
Context ctx = new Context(client, client.Client.RemoteEndPoint.ToString(), isOutbound: true);
ctx.OnMessageReceived += oPeerMessageReceived;
OnClientConnected?.Invoke(ctx);
try
{
await ctx.RunLoop(cancellationToken);
}
catch (TaskCanceledException)
{
}
catch (System.IO.IOException)
{
ctx.ShouldDisconnect = true;
}
finally
{
client.Close();
}
}
19
Source : DnsServer.cs
with Apache License 2.0
from alexreinert
with Apache License 2.0
from alexreinert
private async void HandleTcpListenerAsync()
{
TcpClient client = null;
try
{
try
{
client = await _tcpListener.AcceptTcpClientAsync();
ClientConnectedEventArgs clientConnectedEventArgs = new ClientConnectedEventArgs(ProtocolType.Tcp, (IPEndPoint) client.Client.RemoteEndPoint);
await ClientConnected.RaiseAsync(this, clientConnectedEventArgs);
if (clientConnectedEventArgs.RefuseConnect)
return;
}
finally
{
lock (_listenerLock)
{
_hasActiveTcpListener = false;
}
}
StartTcpListenerTask();
using (NetworkStream stream = client.GetStream())
{
while (true)
{
byte[] buffer = await ReadIntoBufferAsync(client, stream, 2);
if (buffer == null) // client disconneted while reading or timeout
break;
int offset = 0;
int length = DnsMessageBase.ParseUShort(buffer, ref offset);
buffer = await ReadIntoBufferAsync(client, stream, length);
if (buffer == null) // client disconneted while reading or timeout
{
throw new Exception("Client disconnted or timed out while sending data");
}
DnsMessageBase query;
byte[] tsigMac;
try
{
query = DnsMessageBase.CreateByFlag(buffer, TsigKeySelector, null);
tsigMac = query.TSigOptions?.Mac;
}
catch (Exception e)
{
throw new Exception("Error parsing dns query", e);
}
DnsMessageBase response;
try
{
response = await ProcessMessageAsync(query, ProtocolType.Tcp, (IPEndPoint) client.Client.RemoteEndPoint);
}
catch (Exception ex)
{
OnExceptionThrownAsync(ex);
response = DnsMessageBase.CreateByFlag(buffer, TsigKeySelector, null);
response.IsQuery = false;
response.AdditionalRecords.Clear();
response.AuthorityRecords.Clear();
response.ReturnCode = ReturnCode.ServerFailure;
}
byte[] newTsigMac;
length = response.Encode(true, tsigMac, false, out buffer, out newTsigMac);
if (length <= 65535)
{
await stream.WriteAsync(buffer, 0, length);
}
else
{
if ((response.Questions.Count == 0) || (response.Questions[0].RecordType != RecordType.Axfr))
{
OnExceptionThrownAsync(new ArgumentException("The length of the serialized response is greater than 65,535 bytes"));
response = DnsMessageBase.CreateByFlag(buffer, TsigKeySelector, null);
response.IsQuery = false;
response.AdditionalRecords.Clear();
response.AuthorityRecords.Clear();
response.ReturnCode = ReturnCode.ServerFailure;
length = response.Encode(true, tsigMac, false, out buffer, out newTsigMac);
await stream.WriteAsync(buffer, 0, length);
}
else
{
bool isSubSequentResponse = false;
while (true)
{
List<DnsRecordBase> nextPacketRecords = new List<DnsRecordBase>();
while (length > 65535)
{
int lastIndex = Math.Min(500, response.AnswerRecords.Count / 2);
int removeCount = response.AnswerRecords.Count - lastIndex;
nextPacketRecords.InsertRange(0, response.AnswerRecords.GetRange(lastIndex, removeCount));
response.AnswerRecords.RemoveRange(lastIndex, removeCount);
length = response.Encode(true, tsigMac, isSubSequentResponse, out buffer, out newTsigMac);
}
await stream.WriteAsync(buffer, 0, length);
if (nextPacketRecords.Count == 0)
break;
isSubSequentResponse = true;
tsigMac = newTsigMac;
response.AnswerRecords = nextPacketRecords;
length = response.Encode(true, tsigMac, true, out buffer, out newTsigMac);
}
}
}
// Since support for multiple tsig signed messages is not finished, just close connection after response to first signed query
if (newTsigMac != null)
break;
}
}
}
catch (Exception ex)
{
OnExceptionThrownAsync(ex);
}
finally
{
try
{
// ReSharper disable once ConstantConditionalAccessQualifier
client?.Close();
}
catch
{
// ignored
}
lock (_listenerLock)
{
_availableTcpListener++;
}
StartTcpListenerTask();
}
}
19
Source : TcpClientExtensions.cs
with Apache License 2.0
from alexreinert
with Apache License 2.0
from alexreinert
public static bool TryConnect(this TcpClient tcpClient, IPEndPoint endPoint, int timeout)
{
IAsyncResult ar = tcpClient.BeginConnect(endPoint.Address, endPoint.Port, null, null);
var wh = ar.AsyncWaitHandle;
try
{
if (!ar.AsyncWaitHandle.WaitOne(TimeSpan.FromMilliseconds(timeout), false))
{
tcpClient.Close();
return false;
}
tcpClient.EndConnect(ar);
return true;
}
finally
{
wh.Close();
}
}
19
Source : TcpClientExtensions.cs
with Apache License 2.0
from alexreinert
with Apache License 2.0
from alexreinert
public static async Task<bool> TryConnectAsync(this TcpClient tcpClient, IPAddress address, int port, int timeout, CancellationToken token)
{
var connectTask = tcpClient.ConnectAsync(address, port);
var timeoutTask = Task.Delay(timeout, token);
await Task.WhenAny(connectTask, timeoutTask);
if (connectTask.IsCompleted)
return true;
tcpClient.Close();
return false;
}
19
Source : TcpServer.cs
with MIT License
from alexwahl
with MIT License
from alexwahl
private async Task ListenForClientConnection(CancellationToken ct)
{
this.tcpListener.Start();
ct.Register(CancelComm);
while (!ct.IsCancellationRequested)
{
//blocks until a client has connected to the server
TcpClient client = await this.tcpListener.AcceptTcpClientAsync();
//only one client can connect !
NetworkStream clientStream = client.GetStream();
Connection_established();
byte[] message = new byte[4096];
int bytesRead;
while (!ct.IsCancellationRequested)
{
try
{
bytesRead = 0;
//read message from client
bytesRead = await clientStream.ReadAsync(message, 0, 4096, ct).ConfigureAwait(true);
var str = System.Text.Encoding.Default.GetString(message, 0,bytesRead);
var answer = rigctrl.ExecCommand(str);
var answerBytes = (new System.Text.ASCIIEncoding()).GetBytes(answer);
await clientStream.WriteAsync(answerBytes, 0, answerBytes.Length,ct).ConfigureAwait(true);
}
catch
{
//a socket error has occured
break;
}
}
client.Close();
connection_lost();
}
}
19
Source : DnsClientBase.cs
with Apache License 2.0
from alexreinert
with Apache License 2.0
from alexreinert
protected TMessage SendMessage<TMessage>(TMessage message)
where TMessage : DnsMessageBase, new()
{
int messageLength;
byte[] messageData;
DnsServer.SelectTsigKey tsigKeySelector;
byte[] tsigOriginalMac;
PrepareMessage(message, out messageLength, out messageData, out tsigKeySelector, out tsigOriginalMac);
bool sendByTcp = ((messageLength > MaximumQueryMessageSize) || message.IsTcpUsingRequested || !IsUdpEnabled);
var endpointInfos = GetEndpointInfos();
for (int i = 0; i < endpointInfos.Count; i++)
{
TcpClient tcpClient = null;
NetworkStream tcpStream = null;
try
{
var endpointInfo = endpointInfos[i];
IPAddress responderAddress;
byte[] resultData = sendByTcp ? QueryByTcp(endpointInfo.ServerAddress, messageData, messageLength, ref tcpClient, ref tcpStream, out responderAddress) : QueryByUdp(endpointInfo, messageData, messageLength, out responderAddress);
if (resultData != null)
{
TMessage result;
try
{
result = DnsMessageBase.Parse<TMessage>(resultData, tsigKeySelector, tsigOriginalMac);
}
catch (Exception e)
{
Trace.TraceError("Error on dns query: " + e);
continue;
}
if (!ValidateResponse(message, result))
continue;
if ((result.ReturnCode == ReturnCode.ServerFailure) && (i != endpointInfos.Count - 1))
{
continue;
}
if (result.IsTcpResendingRequested)
{
resultData = QueryByTcp(responderAddress, messageData, messageLength, ref tcpClient, ref tcpStream, out responderAddress);
if (resultData != null)
{
TMessage tcpResult;
try
{
tcpResult = DnsMessageBase.Parse<TMessage>(resultData, tsigKeySelector, tsigOriginalMac);
}
catch (Exception e)
{
Trace.TraceError("Error on dns query: " + e);
continue;
}
if (tcpResult.ReturnCode == ReturnCode.ServerFailure)
{
if (i != endpointInfos.Count - 1)
{
continue;
}
}
else
{
result = tcpResult;
}
}
}
bool isTcpNextMessageWaiting = result.IsTcpNextMessageWaiting(false);
bool isSucessfullFinished = true;
while (isTcpNextMessageWaiting)
{
resultData = QueryByTcp(responderAddress, null, 0, ref tcpClient, ref tcpStream, out responderAddress);
if (resultData != null)
{
TMessage tcpResult;
try
{
tcpResult = DnsMessageBase.Parse<TMessage>(resultData, tsigKeySelector, tsigOriginalMac);
}
catch (Exception e)
{
Trace.TraceError("Error on dns query: " + e);
isSucessfullFinished = false;
break;
}
if (tcpResult.ReturnCode == ReturnCode.ServerFailure)
{
isSucessfullFinished = false;
break;
}
else
{
result.AnswerRecords.AddRange(tcpResult.AnswerRecords);
isTcpNextMessageWaiting = tcpResult.IsTcpNextMessageWaiting(true);
}
}
else
{
isSucessfullFinished = false;
break;
}
}
if (isSucessfullFinished)
return result;
}
}
finally
{
try
{
tcpStream?.Dispose();
tcpClient?.Close();
}
catch
{
// ignored
}
}
}
return null;
}
19
Source : DnsClientBase.cs
with Apache License 2.0
from alexreinert
with Apache License 2.0
from alexreinert
protected async Task<TMessage> SendMessageAsync<TMessage>(TMessage message, CancellationToken token)
where TMessage : DnsMessageBase, new()
{
int messageLength;
byte[] messageData;
DnsServer.SelectTsigKey tsigKeySelector;
byte[] tsigOriginalMac;
PrepareMessage(message, out messageLength, out messageData, out tsigKeySelector, out tsigOriginalMac);
bool sendByTcp = ((messageLength > MaximumQueryMessageSize) || message.IsTcpUsingRequested || !IsUdpEnabled);
var endpointInfos = GetEndpointInfos();
for (int i = 0; i < endpointInfos.Count; i++)
{
token.ThrowIfCancellationRequested();
var endpointInfo = endpointInfos[i];
QueryResponse resultData = null;
try
{
resultData = await (sendByTcp ? QueryByTcpAsync(endpointInfo.ServerAddress, messageData, messageLength, null, null, token) : QuerySingleResponseByUdpAsync(endpointInfo, messageData, messageLength, token));
if (resultData == null)
return null;
TMessage result;
try
{
result = DnsMessageBase.Parse<TMessage>(resultData.Buffer, tsigKeySelector, tsigOriginalMac);
}
catch (Exception e)
{
Trace.TraceError("Error on dns query: " + e);
continue;
}
if (!ValidateResponse(message, result))
continue;
if ((result.ReturnCode != ReturnCode.NoError) && (result.ReturnCode != ReturnCode.NxDomain) && (i != endpointInfos.Count - 1))
continue;
if (result.IsTcpResendingRequested)
{
resultData = await QueryByTcpAsync(resultData.ResponderAddress, messageData, messageLength, resultData.TcpClient, resultData.TcpStream, token);
if (resultData != null)
{
TMessage tcpResult;
try
{
tcpResult = DnsMessageBase.Parse<TMessage>(resultData.Buffer, tsigKeySelector, tsigOriginalMac);
}
catch (Exception e)
{
Trace.TraceError("Error on dns query: " + e);
return null;
}
if (tcpResult.ReturnCode == ReturnCode.ServerFailure)
{
return result;
}
else
{
result = tcpResult;
}
}
}
bool isTcpNextMessageWaiting = result.IsTcpNextMessageWaiting(false);
bool isSucessfullFinished = true;
while (isTcpNextMessageWaiting)
{
// ReSharper disable once PossibleNullReferenceException
resultData = await QueryByTcpAsync(resultData.ResponderAddress, null, 0, resultData.TcpClient, resultData.TcpStream, token);
if (resultData != null)
{
TMessage tcpResult;
try
{
tcpResult = DnsMessageBase.Parse<TMessage>(resultData.Buffer, tsigKeySelector, tsigOriginalMac);
}
catch (Exception e)
{
Trace.TraceError("Error on dns query: " + e);
isSucessfullFinished = false;
break;
}
if (tcpResult.ReturnCode == ReturnCode.ServerFailure)
{
isSucessfullFinished = false;
break;
}
else
{
result.AnswerRecords.AddRange(tcpResult.AnswerRecords);
isTcpNextMessageWaiting = tcpResult.IsTcpNextMessageWaiting(true);
}
}
else
{
isSucessfullFinished = false;
break;
}
}
if (isSucessfullFinished)
return result;
}
finally
{
if (resultData != null)
{
try
{
resultData.TcpStream?.Dispose();
resultData.TcpClient?.Close();
}
catch
{
// ignored
}
}
}
}
return null;
}
19
Source : Session.cs
with Apache License 2.0
from AlexWan
with Apache License 2.0
from AlexWan
public void Dispose()
{
_stream.Close();
_stream.Dispose();
_tcpClient.Close();
}
19
Source : AdminPanelClient.cs
with Apache License 2.0
from AlexWan
with Apache License 2.0
from AlexWan
protected internal void Close()
{
Stream?.Close();
_client?.Close();
}
19
Source : ProxyClient.cs
with Apache License 2.0
from AlexWan
with Apache License 2.0
from AlexWan
public void Close()
{
_stream?.Close();
_client?.Close();
_client?.Dispose();
_client = null;
}
19
Source : TcpServer.cs
with Apache License 2.0
from AlexWan
with Apache License 2.0
from AlexWan
protected internal void Listen()
{
try
{
_tcpListener = new TcpListener(IPAddress.Any, Port);
_tcpListener.Start();
Task.Run(Sender);
Started?.Invoke();
while (true)
{
TcpClient tcpClient = _tcpListener.AcceptTcpClient();
var ip = ((IPEndPoint)tcpClient.Client.RemoteEndPoint).Address.ToString();
if (!_permittedIp.Contains(ip))
{
tcpClient.Close();
continue;
}
AdminPanelClient adminPanelClient = new AdminPanelClient(tcpClient, this);
adminPanelClient.Token = PermittedToken;
Thread clientThread = new Thread(adminPanelClient.Process);
clientThread.Start();
}
}
catch (Exception ex)
{
Disconnect();
Disconnected?.Invoke();
}
}
19
Source : TcpServer.cs
with Apache License 2.0
from AlexWan
with Apache License 2.0
from AlexWan
protected internal void Listen()
{
try
{
_tcpListener = new TcpListener(IPAddress.Any, ExitPort);
_tcpListener.Start();
Task.Run(Sender);
Started?.Invoke();
while (true)
{
TcpClient tcpClient = _tcpListener.AcceptTcpClient();
var ip = ((IPEndPoint)tcpClient.Client.RemoteEndPoint).Address.ToString();
if (!_permittedIp.Contains(ip))
{
tcpClient.Close();
continue;
}
AdminPanelClient clientObject = new AdminPanelClient(tcpClient, this);
clientObject.Token = PermittedToken;
Thread clientThread = new Thread(clientObject.Process);
clientThread.Start();
}
}
catch (Exception ex)
{
Disconnect();
Disconnected?.Invoke();
}
}
19
Source : PeerCommunicator.cs
with MIT License
from aljazsim
with MIT License
from aljazsim
public void Dispose()
{
lock (this.locker)
{
if (!this.IsDisposed)
{
Debug.WriteLine($"disposing peer communicator for {this.tcp.Client.RemoteEndPoint}");
this.IsDisposed = true;
if (this.stream != null)
{
this.stream.Flush();
this.stream.Close();
this.stream.Dispose();
this.stream = null;
}
if (this.tcp != null)
{
this.tcp.Close();
this.tcp.Dispose();
this.tcp = null;
}
}
}
}
19
Source : TorrentClient.cs
with MIT License
from aljazsim
with MIT License
from aljazsim
private void Listen()
{
int timeout = (int)TimeSpan.FromSeconds(5).TotalMilliseconds;
int bufferSize = 1024 * 1024;
int bytesRead;
int offset = 0;
byte[] buffer = new byte[bufferSize];
TcpClient tcp;
TransferManager transfer;
while (!this.IsDisposed &&
this.IsRunning)
{
tcp = this.server.AcceptTcpClient();
tcp.Client.SendTimeout = timeout;
tcp.SendBufferSize = bufferSize;
tcp.Client.ReceiveTimeout = timeout;
tcp.ReceiveBufferSize = bufferSize;
offset = 0;
try
{
bytesRead = tcp.GetStream().Read(buffer, 0, buffer.Length);
if (bytesRead > 0)
{
foreach (var message in PeerMessage.Decode(buffer, ref offset, bytesRead))
{
if (message is HandshakeMessage)
{
lock (((IDictionary)this.transfers).SyncRoot)
{
if (this.transfers.TryGetValue(message.As<HandshakeMessage>().InfoHash, out transfer))
{
transfer.AddLeecher(tcp, message.As<HandshakeMessage>().PeerId);
}
else
{
Debug.WriteLine($"invalid torrent info hash: {message.As<HandshakeMessage>().InfoHash} received");
}
}
}
}
}
}
catch (IOException ex)
{
// something is wrong with remote peer -> ignore it
Debug.WriteLine($"could not read stream from {tcp.Client.RemoteEndPoint}: {ex.Message}");
// close the connection
tcp.Close();
tcp = null;
}
}
}
19
Source : TransferManager.cs
with MIT License
from aljazsim
with MIT License
from aljazsim
private void PeerConnected(IAsyncResult ar)
{
AsyncConnectData data;
TcpClient tcp;
Peer peer;
IPEndPoint endpoint;
data = ar.AsyncState as AsyncConnectData;
endpoint = data.Endpoint;
try
{
tcp = data.Tcp;
tcp.EndConnect(ar);
lock (((IDictionary)this.peers).SyncRoot)
{
if (this.peers.ContainsKey(endpoint))
{
// peer is already present
tcp.Close();
tcp = null;
}
else
{
Debug.WriteLine($"adding seeding peer {endpoint} to torrent {this.TorrentInfo.InfoHash}");
// add new peer
peer = new Peer(new PeerCommunicator(this.throttlingManager, tcp), this.pieceManager, this.PeerId);
peer.CommunicationErrorOccurred += this.Peer_CommunicationErrorOccurred;
this.peers.Add(endpoint, peer);
}
}
}
catch (SocketException ex)
{
Debug.WriteLine($"could not connect to peer {endpoint}: {ex.Message}");
}
catch (IOException ex)
{
Debug.WriteLine($"connection to peer {endpoint} was closed: {ex.Message}");
}
}
19
Source : TransferManager.cs
with MIT License
from aljazsim
with MIT License
from aljazsim
public void AddLeecher(TcpClient tcp, string peerId)
{
tcp.CannotBeNull();
peerId.CannotBeNull();
Peer peer;
int maxLeechers = 10;
lock (((IDictionary)this.peers).SyncRoot)
{
if (!this.peers.ContainsKey(tcp.Client.RemoteEndPoint as IPEndPoint))
{
if (this.LeechingPeerCount < maxLeechers)
{
Debug.WriteLine($"adding leeching peer {tcp.Client.RemoteEndPoint} to torrent {this.TorrentInfo.InfoHash}");
// setup tcp client
tcp.ReceiveBufferSize = (int)Math.Max(this.TorrentInfo.BlockLength, this.TorrentInfo.PieceHashes.Count()) + 100;
tcp.SendBufferSize = tcp.ReceiveBufferSize;
tcp.Client.ReceiveTimeout = (int)TimeSpan.FromSeconds(60).TotalMilliseconds;
tcp.Client.SendTimeout = tcp.Client.ReceiveTimeout;
// add new peer
peer = new Peer(new PeerCommunicator(this.throttlingManager, tcp), this.pieceManager, this.PeerId, peerId);
peer.CommunicationErrorOccurred += this.Peer_CommunicationErrorOccurred;
this.peers.Add(tcp.Client.RemoteEndPoint as IPEndPoint, peer);
}
else
{
tcp.Close();
}
}
else
{
tcp.Close();
}
}
}
19
Source : SocketListener.cs
with MIT License
from amazingalek
with MIT License
from amazingalek
private void ListenToSocket()
{
var localAddress = IPAddress.Parse(Constants.LocalAddress);
_server = new TcpListener(localAddress, _port);
_server.Start();
var bytes = new byte[BufferSize];
while (true)
{
var client = _server.AcceptTcpClient();
ConsoleUtils.WriteByType(MessageType.Success, "Console connected to socket!");
var stream = client.GetStream();
int i;
while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
{
ProcessMessage(bytes, i);
}
ConsoleUtils.WriteByType(MessageType.Success, "Closing client!");
client.Close();
}
}
19
Source : OpenVPNSession.cs
with GNU General Public License v3.0
from Amebis
with GNU General Public License v3.0
from Amebis
protected override void DoRun()
{
Wizard.Dispatcher.Invoke(DispatcherPriority.Normal, (Action)(() => Wizard.TaskCount++));
try
{
try
{
// Start OpenVPN management interface on IPv4 loopack interface (any TCP free port).
var mgmtServer = new TcpListener(IPAddress.Loopback, 0);
mgmtServer.Start();
try
{
try
{
// Purge stale log files.
var timestamp = DateTime.UtcNow.Subtract(new TimeSpan(30, 0, 0, 0));
foreach (var f in Directory.EnumerateFiles(WorkingFolder, "*.txt", SearchOption.TopDirectoryOnly))
{
SessionAndWindowInProgress.Token.ThrowIfCancellationRequested();
if (File.GetLastWriteTimeUtc(f) <= timestamp)
{
try { File.Delete(LogPath); }
catch { }
}
}
}
catch (OperationCanceledException) { throw; }
catch (Exception) { /* Failure to remove stale log files is not fatal. */ }
try
{
// Save OpenVPN configuration file.
using (var fs = new FileStream(
ConfigurationPath,
FileMode.Create,
FileAccess.Write,
FileShare.Read,
1048576,
FileOptions.SequentialScan))
using (var sw = new StreamWriter(fs))
{
// Save profile's configuration to file.
if (Properties.SettingsEx.Default.OpenVPNRemoveOptions is StringCollection openVPNRemoveOptions)
{
// Remove options on the OpenVPNRemoveOptions list on the fly.
using (var sr = new StringReader(ProfileConfig))
{
string inlineTerm = null;
bool inlineRemove = false;
for (; ; )
{
var line = sr.ReadLine();
if (line == null)
break;
var trimmedLine = line.Trim();
if (!string.IsNullOrEmpty(trimmedLine))
{
// Not an empty line.
if (inlineTerm == null)
{
// Not inside an inline option block = Regular parsing mode.
if (!trimmedLine.StartsWith("#") &&
!trimmedLine.StartsWith(";"))
{
// Not a comment.
var option = eduOpenVPN.Configuration.ParseParams(trimmedLine);
if (option.Count > 0)
{
if (option[0].StartsWith("<") && !option[0].StartsWith("</") && option[0].EndsWith(">"))
{
// Start of an inline option.
var o = option[0].Substring(1, option[0].Length - 2);
inlineTerm = "</" + o + ">";
inlineRemove = openVPNRemoveOptions.Contains(o);
if (inlineRemove)
{
sw.WriteLine("# Commented by OpenVPNRemoveOptions setting:");
line = "# " + line;
}
}
else if (openVPNRemoveOptions.Contains(option[0]))
{
sw.WriteLine("# Commented by OpenVPNRemoveOptions setting:");
line = "# " + line;
}
}
}
}
else
{
// Inside an inline option block.
if (inlineRemove)
{
// Remove the inline option content.
line = "# " + line;
}
if (trimmedLine == inlineTerm)
{
// Inline option terminator found. Returning to regular parsing mode.
inlineTerm = null;
}
}
}
sw.WriteLine(line);
}
}
}
else
sw.Write(ProfileConfig);
// Append eduVPN Client specific configuration directives.
sw.WriteLine();
sw.WriteLine();
sw.WriteLine("# eduVPN Client for Windows");
// Introduce ourself (to OpenVPN server).
var replacedembly = replacedembly.GetExecutingreplacedembly();
var replacedemblyreplacedleAttribute = Attribute.GetCustomAttributes(replacedembly, typeof(replacedemblyreplacedleAttribute)).SingleOrDefault() as replacedemblyreplacedleAttribute;
var replacedemblyVersion = replacedembly?.GetName()?.Version;
sw.WriteLine("setenv IV_GUI_VER " + eduOpenVPN.Configuration.EscapeParamValue(replacedemblyreplacedleAttribute?.replacedle + " " + replacedemblyVersion?.ToString()));
// Configure log file (relative to WorkingFolder).
sw.WriteLine("log-append " + eduOpenVPN.Configuration.EscapeParamValue(ConnectionId + ".txt"));
// Configure interaction between us and openvpn.exe.
sw.WriteLine("management " + eduOpenVPN.Configuration.EscapeParamValue(((IPEndPoint)mgmtServer.LocalEndpoint).Address.ToString()) + " " + eduOpenVPN.Configuration.EscapeParamValue(((IPEndPoint)mgmtServer.LocalEndpoint).Port.ToString()) + " stdin");
sw.WriteLine("management-client");
sw.WriteLine("management-hold");
sw.WriteLine("management-query-preplacedwords");
sw.WriteLine("management-query-remote");
// Configure client certificate.
sw.WriteLine("cert " + eduOpenVPN.Configuration.EscapeParamValue(ConnectingProfile.Server.ClientCertificatePath));
sw.WriteLine("key " + eduOpenVPN.Configuration.EscapeParamValue(ConnectingProfile.Server.ClientCertificatePath));
// Ask when username/preplacedword is denied.
sw.WriteLine("auth-retry interact");
sw.WriteLine("auth-nocache");
// Set Wintun interface to be used.
sw.Write("windows-driver wintun\n");
sw.Write("dev-node " + eduOpenVPN.Configuration.EscapeParamValue(Properties.Settings.Default.Clientreplacedle) + "\n");
#if DEBUG
// Renegotiate data channel every 5 minutes in debug versions.
sw.WriteLine("reneg-sec 300");
#endif
if (Environment.OSVersion.Version < new Version(6, 2))
{
// Windows 7 is using tiny 8kB send/receive socket buffers by default.
// Increase to 64kB which is default from Windows 8 on.
sw.WriteLine("sndbuf 65536");
sw.WriteLine("rcvbuf 65536");
}
var openVPNAddOptions = Properties.SettingsEx.Default.OpenVPNAddOptions;
if (!string.IsNullOrWhiteSpace(openVPNAddOptions))
{
sw.WriteLine();
sw.WriteLine();
sw.WriteLine("# Added by OpenVPNAddOptions setting:");
sw.WriteLine(openVPNAddOptions);
}
}
}
catch (OperationCanceledException) { throw; }
catch (Exception ex) { throw new AggregateException(string.Format(Resources.Strings.ErrorSavingProfileConfiguration, ConfigurationPath), ex); }
bool retry;
do
{
retry = false;
// Connect to OpenVPN Interactive Service to launch the openvpn.exe.
using (var openvpnInteractiveServiceConnection = new eduOpenVPN.InteractiveService.Session())
{
var mgmtPreplacedword = Membership.GeneratePreplacedword(16, 6);
try
{
openvpnInteractiveServiceConnection.Connect(
string.Format("openvpn{0}\\service", InstanceName),
WorkingFolder,
new string[] { "--config", ConnectionId + ".conf", },
mgmtPreplacedword + "\n",
3000,
SessionAndWindowInProgress.Token);
}
catch (OperationCanceledException) { throw; }
catch (Exception ex) { throw new AggregateException(Resources.Strings.ErrorInteractiveService, ex); }
try
{
// Wait and accept the openvpn.exe on our management interface (--management-client parameter).
var mgmtClientTask = mgmtServer.AcceptTcpClientAsync();
try { mgmtClientTask.Wait(30000, SessionAndWindowInProgress.Token); }
catch (AggregateException ex) { throw ex.InnerException; }
var mgmtClient = mgmtClientTask.Result;
try
{
// Start the management session.
ManagementSession.Start(mgmtClient.GetStream(), mgmtPreplacedword, SessionAndWindowInProgress.Token);
// Initialize session and release openvpn.exe to get started.
ManagementSession.SetVersion(3, SessionAndWindowInProgress.Token);
ManagementSession.ReplayAndEnableState(SessionAndWindowInProgress.Token);
ManagementSession.ReplayAndEnableEcho(SessionAndWindowInProgress.Token);
ManagementSession.SetByteCount(5, SessionAndWindowInProgress.Token);
ManagementSession.ReleaseHold(SessionAndWindowInProgress.Token);
Wizard.Dispatcher.Invoke(DispatcherPriority.Normal, (Action)(() => Wizard.TaskCount--));
try
{
// Wait for the session to end gracefully.
ManagementSession.Monitor.Join();
if (ManagementSession.Error != null && !(ManagementSession.Error is OperationCanceledException))
{
// Session reported an error. Retry.
retry = true;
}
}
finally { Wizard.Dispatcher.Invoke(DispatcherPriority.Normal, (Action)(() => Wizard.TaskCount++)); }
}
finally { mgmtClient.Close(); }
}
finally
{
Wizard.Dispatcher.Invoke(DispatcherPriority.Normal, (Action)(
() =>
{
// Cleanup status properties.
State = SessionStatusType.Disconnecting;
StateDescription = Resources.Strings.OpenVPNStateTypeExiting;
TunnelAddress = null;
IPv6TunnelAddress = null;
ConnectedAt = null;
BytesIn = null;
BytesOut = null;
}));
// Wait for openvpn.exe to finish. Maximum 30s.
try { Process.GetProcessById(openvpnInteractiveServiceConnection.ProcessId)?.WaitForExit(30000); }
catch (ArgumentException) { }
}
}
} while (retry);
}
finally
{
mgmtServer.Stop();
}
}
finally
{
// Delete profile configuration file. If possible.
try { File.Delete(ConfigurationPath); }
catch { }
}
}
finally
{
Wizard.Dispatcher.Invoke(DispatcherPriority.Normal, (Action)(
() =>
{
// Cleanup status properties.
State = SessionStatusType.Disconnected;
StateDescription = "";
Wizard.TaskCount--;
}));
PropertyUpdater.Stop();
}
}
19
Source : CheatEngineServer.cs
with GNU General Public License v3.0
from andreluis034
with GNU General Public License v3.0
from andreluis034
private void HandleReceivedClient(TcpClient client)
{
var clientStream = client.GetStream();
var reader = new BinaryReader(clientStream);
var writer = new BinaryWriter(clientStream);
while (true)
{
try
{
var command = this.packetManager.ReadNextCommand(reader);
var output = this.packetManager.ProcessAndGetBytes(command);
/* if(command.CommandType != CommandType.CMD_READPROCESSMEMORY)
Console.WriteLine(BitConverter.ToString(output).Replace("-", ""));*/
// Console.WriteLine("{0} returned {1} bytes", command.CommandType, output.Length);
writer.Write(output);
writer.Flush();
// Handle(stream, writer, cmd);
}
catch(EndOfStreamException)
{
client.Close();
break;
}
catch (Exception e)
{
Console.WriteLine(e + ": "+ e.Message);
Console.WriteLine(e.StackTrace);
client.Close();
break;
}
}
}
19
Source : WebSocketServer.cs
with MIT License
from andruzzzhka
with MIT License
from andruzzzhka
private void receiveRequest ()
{
while (true) {
TcpClient cl = null;
try {
cl = _listener.AcceptTcpClient ();
ThreadPool.QueueUserWorkItem (
state => {
try {
var ctx = new TcpListenerWebSocketContext (
cl, null, _secure, _sslConfigInUse, _log
);
processRequest (ctx);
}
catch (Exception ex) {
_log.Error (ex.Message);
_log.Debug (ex.ToString ());
cl.Close ();
}
}
);
}
catch (SocketException ex) {
if (_state == ServerState.ShuttingDown) {
_log.Info ("The underlying listener is stopped.");
break;
}
_log.Fatal (ex.Message);
_log.Debug (ex.ToString ());
break;
}
catch (Exception ex) {
_log.Fatal (ex.Message);
_log.Debug (ex.ToString ());
if (cl != null)
cl.Close ();
break;
}
}
if (_state != ServerState.ShuttingDown)
abort ();
}
19
Source : TcpListenerWebSocketContext.cs
with MIT License
from andruzzzhka
with MIT License
from andruzzzhka
internal void Close ()
{
_stream.Close ();
_tcpClient.Close ();
}
19
Source : TcpListenerWebSocketContext.cs
with MIT License
from andruzzzhka
with MIT License
from andruzzzhka
internal void Close (HttpStatusCode code)
{
var res = HttpResponse.CreateCloseResponse (code);
var bytes = res.ToByteArray ();
_stream.Write (bytes, 0, bytes.Length);
_stream.Close ();
_tcpClient.Close ();
}
19
Source : SmartHomeProtocolMessage.cs
with Apache License 2.0
from anthturner
with Apache License 2.0
from anthturner
internal dynamic Execute(string hostname, int port)
{
var messageToSend = SmartHomeProtocolEncoder.Encrypt(JSON);
var client = new TcpClient(hostname, port);
byte[] packet = new byte[0];
using (var stream = client.GetStream())
{
stream.Write(messageToSend, 0, messageToSend.Length);
int targetSize = 0;
var buffer = new List<byte>();
while (true)
{
var chunk = new byte[1024];
var bytesReceived = stream.Read(chunk, 0, chunk.Length);
if (!buffer.Any())
{
var lengthBytes = chunk.Take(4).ToArray();
if (BitConverter.IsLittleEndian) // this value needs to be in big-endian
lengthBytes = lengthBytes.Reverse().ToArray();
targetSize = (int)BitConverter.ToUInt32(lengthBytes, 0);
}
buffer.AddRange(chunk.Take(bytesReceived));
if (buffer.Count == targetSize + 4)
break;
}
packet = buffer.Skip(4).Take(targetSize).ToArray();
}
client.Close();
var decrypted = Encoding.UTF8.GetString(SmartHomeProtocolEncoder.Decrypt(packet)).Trim('\0');
var subResult = (dynamic)((JObject)JObject.Parse(decrypted)[System])[Command];
if (subResult["err_code"] != null && subResult.err_code != 0)
throw new Exception($"Protocol error {subResult.err_code} ({subResult.err_msg})");
return subResult;
}
19
Source : ModbusTcpClient.cs
with GNU Lesser General Public License v3.0
from Apollo3zehn
with GNU Lesser General Public License v3.0
from Apollo3zehn
public void Connect(IPEndPoint remoteEndpoint, ModbusEndianness endianness)
{
base.SwapBytes = BitConverter.IsLittleEndian && endianness == ModbusEndianness.BigEndian
|| !BitConverter.IsLittleEndian && endianness == ModbusEndianness.LittleEndian;
_frameBuffer = new ModbusFrameBuffer(260);
_tcpClient?.Close();
_tcpClient = new TcpClient();
if (!_tcpClient.ConnectAsync(remoteEndpoint.Address, remoteEndpoint.Port).Wait(this.ConnectTimeout))
throw new Exception(ErrorMessage.ModbusClient_TcpConnectTimeout);
_networkStream = _tcpClient.GetStream();
_networkStream.ReadTimeout = this.ReadTimeout;
_networkStream.WriteTimeout = this.WriteTimeout;
}
19
Source : ModbusTcpClient.cs
with GNU Lesser General Public License v3.0
from Apollo3zehn
with GNU Lesser General Public License v3.0
from Apollo3zehn
public void Disconnect()
{
_tcpClient?.Close();
_frameBuffer?.Dispose();
// workaround for https://github.com/Apollo3zehn/FluentModbus/issues/44#issuecomment-747321152
if (RuntimeInformation.FrameworkDescription.StartsWith(".NET Framework", StringComparison.OrdinalIgnoreCase))
_tcpClient = null;
}
19
Source : ModbusTcpRequestHandler.cs
with GNU Lesser General Public License v3.0
from Apollo3zehn
with GNU Lesser General Public License v3.0
from Apollo3zehn
protected override void Dispose(bool disposing)
{
if (!disposedValue)
{
if (disposing)
_tcpClient.Close();
disposedValue = true;
}
base.Dispose(disposing);
}
19
Source : Socks5Server.cs
with MIT License
from araditc
with MIT License
from araditc
protected virtual void Dispose(bool disposing) {
if (!disposed) {
// Indicate that the instance has been disposed.
disposed = true;
// Get rid of managed resources.
if (disposing) {
if (stream != null)
stream.Dispose();
stream = null;
if (client != null)
client.Close();
client = null;
}
// Get rid of unmanaged resources.
}
}
See More Examples