public BeginRead ( byte buffer, int offset, int size, AsyncCallback callback, Object state ) : IAsyncResult | ||
buffer | byte | |
offset | int | |
size | int | |
callback | AsyncCallback | |
state | Object | |
return | IAsyncResult |
public RiceClient(TcpClient tcp, RiceListener parent, bool exchangeRequired) { this.tcp = tcp; this.parent = parent; this.exchangeRequired = exchangeRequired; ns = tcp.GetStream(); Alive = true; try { if (exchangeRequired) { buffer = new byte[56]; bytesToRead = buffer.Length; ns.BeginRead(buffer, 0, 56, onExchange, null); } else { buffer = new byte[4]; bytesToRead = buffer.Length; ns.BeginRead(buffer, 0, 4, onHeader, null); } } catch (Exception ex) { Kill(ex); } }
public void ReconnectPipe() { if (null != m_tcpConnection) { m_tcpConnection.Client.Close(); m_tcpStream = null; } m_tcpConnection = new SOCK.TcpClient(); NET.IPEndPoint remoteEp = null; m_Settings.WriteMessageToLog( LogMessageType.Information, string.Format( CultureInfo.InvariantCulture, "Connecting to {0}:{1}...", m_Settings.ClientServerHostIp, m_Settings.ClientServerPort ) ); bool bOk = false; while (!bOk && !m_ShuttingDown) { try { if (null == remoteEp) { remoteEp = new NET.IPEndPoint(m_Settings.ClientServerHostIp, m_Settings.ClientServerPort); // Error if DNS is not avaliable } if (null != remoteEp) { m_tcpConnection.Connect(remoteEp); bOk = true; } } catch (Exception) { } } if (m_ShuttingDown) { return; } m_tcpStream = m_tcpConnection.GetStream(); m_tcpStream.BeginRead(m_tcpBuffer, 0, m_tcpBuffer.Length, OnReadFromTcp, null); m_Settings.WriteMessageToLog( LogMessageType.Information, string.Format( CultureInfo.InvariantCulture, "TCP channel connected to SipTunnel server at {0}:{1}.", remoteEp.Address, remoteEp.Port ) ); }
public SocketHandler(TcpClient client) { commandQueue = new Queue<string>(); this.client = client; data = new byte[bufferSize]; netStream = this.client.GetStream(); netStream.BeginRead(data, 0, bufferSize, ReceiveMessage, null); }
public SocketHandler(TcpClient client) { commandQueue = new ConcurrentQueue<string>(); this.client = client; data = new byte[bufferSize]; netStream = this.client.GetStream(); netStream.BeginRead(data, 0, bufferSize, ReceiveMessage, null); separators = new[] { '\n', '\r', '\f', '\0', (char)3 }; }
protected override void ConnectComplete(IAsyncResult result) { Socket.EndConnect(result); NetworkStream = new NetworkStream(Socket); NetworkStream.BeginRead(ReadBuffer, ReadBufferIndex, ReadBuffer.Length, DataReceived, null); SendRawMessage("PASS oauth:{0}", User.Password); SendRawMessage("NICK {0}", User.Nick); }
public void PreparePipe(SOCK.TcpClient client) { if (null == client) { throw new ArgumentNullException("client"); } m_tcpConnection = client; m_tcpStream = m_tcpConnection.GetStream(); m_tcpStream.BeginRead(m_tcpBuffer, 0, m_tcpBuffer.Length, OnReadFromTcp, null); }
static void Main(string[] args) { Console.Write("Bitte geben sie den Hostnamen ein: "); String host_name = Console.ReadLine(); TcpClient client; try { client = new TcpClient(host_name, 666); stream = client.GetStream(); stream.BeginRead(myReadBuffer, 0, myReadBuffer.Length, new AsyncCallback(read_callback), stream); while (client.Connected && stream.CanWrite) { String message = Console.ReadLine() + "\n"; byte[] outputArray = Encoding.UTF8.GetBytes(message); try { stream.Write(outputArray, 0, outputArray.Length); } catch (Exception e) { Console.WriteLine(e.Message); Console.ReadLine(); Environment.Exit(0); } } } catch (ArgumentNullException) { Console.WriteLine("Fehler! Der Hostname darf nicht null sein."); Console.ReadLine(); return; } catch (ArgumentOutOfRangeException) { Console.WriteLine("Ungültiger Port."); Console.ReadLine(); return; } catch (SocketException e) { Console.WriteLine(e.Message); Console.ReadLine(); return; } catch (Exception e) { Console.WriteLine(e.Message); Console.ReadLine(); Environment.Exit(0); } }
private void ReadNetworkData(NetworkStream stream) { try { stream.BeginRead(_buffer, 0, _buffer.Length, ar => { ParseBuffer(stream.EndRead(ar)); ReadNetworkData(stream); }, stream); } catch { } }
public void Connect(TcpClient tcp) { Tcp = tcp; netStream = tcp.GetStream(); IsConnected = true; try { if (netStream.CanRead) netStream.BeginRead(recSizeBuf, 0, recSizeBuf.Length, ReceiveSize, netStream); } catch (Exception ex) { Console.WriteLine(ex.Message); StopClient(); } }
private void Connect(int port, int retryCount) { if (retryCount >= 5) return; try { var client = new TcpClient(); client.Connect("127.0.0.1", port); _currentPort = port; _stream = client.GetStream(); _stream.BeginRead(_buffer, 0, _buffer.Length, ReadCompleted, _stream); IsConnected = true; } catch { Reconnect(retryCount); } }
/*public static void md5(string source) { byte[] data = System.Text.Encoding.UTF8.GetBytes(source); MD5 md = MD5.Create(); byte [] cryptoData = md.ComputeHash(data); Console.WriteLine(System.Text.Encoding.UTF8.GetString(cryptoData)); md.Clear(); } */ public void Listen() { try { new BluetoothClient(); } catch (Exception ex) { var msg = "Bluetooth init failed: " + ex; MessageBox.Show(msg); throw new InvalidOperationException(msg, ex); } Bluetoothlistener = new BluetoothListener(OurServiceClassId); Bluetoothlistener.ServiceName = OurServiceName; Bluetoothlistener.Start(); Bluetoothclient = Bluetoothlistener.AcceptBluetoothClient(); byte[] data = new byte[1024]; Ns = Bluetoothclient.GetStream(); Ns.BeginRead(data, 0, data.Length, new AsyncCallback(ReadCallBack), data); DataAvailable(this, "Begin to read"); }
/// <summary> /// Initializes a new instance of the <see cref="MqttConnection"/> class. /// </summary> /// <param name="server">The server.</param> /// <param name="port">The port.</param> private MqttConnection(string server, int port) { try { // connect and save off the stream. tcpClient = new TcpClient(server, port); } catch (SocketException ex) { throw new ConnectionException( String.Format("The connection to the message broker {0}:{1} could not be made.", server, port), ConnectionState.Faulted, ex); } networkStream = tcpClient.GetStream(); // initiate a read for the next byte which will be the header bytes networkStream.BeginRead(headerByte, 0, 1, ReadComplete, networkStream); }
/// <summary> /// Otevre pripojeni se zadanym IP a portem serveru /// </summary> /// <param name="server">Ip adresa serveru napr 192.168.0.10</param> /// <param name="port">Port serveru</param> /// <param name="asyncRead">Povoleni asynchnoniho cteni </param> /// <returns>Vraci true pokud sepripoji</returns> public bool OpenServer(string server, int port, bool asyncRead) { try { tcp = new TcpClient(server, port); ns = tcp.GetStream(); isConnected = tcp.Connected; if (asyncRead) { AsyncCallback recieveData = new AsyncCallback(OnRecievedData); ns.BeginRead(m_byBuff, 0, m_byBuff.Length, recieveData, null); } } catch (Exception ex) { printOutDbg("\nSetup Recieve Callback failed!\n" + ex.Message); return false; } return true; }
/// <summary> /// Create a new netIO class using a given socket. /// </summary> /// <param name="sock">The socket for this netIO class.</param> public NetIO(Socket sock, Dictionary<ushort, Packet> commandTable, Client client ,ClientManager manager) { this.sock = sock; this.stream = new NetworkStream(sock); this.commandTable = commandTable; this.client = client; this.currentClientManager = manager; this.callbackSize = new AsyncCallback(this.ReceiveSize); this.callbackData = new AsyncCallback(this.ReceiveData); this.nlock = new ReaderWriterLock(); // Use the static key untill the keys have been exchanged this.clientKey = new byte[16]; Encryption.StaticKey.CopyTo(this.clientKey, 0); this.serverKey = new byte[16]; Encryption.StaticKey.CopyTo(this.serverKey, 0); this.isDisconnected = false; // Receive the size of the next packet and call ReceiveSize when finished if (sock.Connected) { try { stream.BeginRead(buffer, 0, 2, this.callbackSize, null); } catch (Exception ex) { Logger.ShowError(ex, null); try//this could crash the gateway somehow,so better ignore the Exception { this.Disconnect(); } catch (Exception) { } Logger.ShowWarning("Invalid packet head from:" + sock.RemoteEndPoint.ToString(), null); return; } } else { this.Disconnect(); return; } }
private static string GetResponse(NetworkStream stream, out string response) { byte[] readBuffer = new byte[32]; var asyncReader = stream.BeginRead(readBuffer, 0, readBuffer.Length, null, null); WaitHandle handle = asyncReader.AsyncWaitHandle; // Give the reader 2seconds to respond with a value bool completed = handle.WaitOne(1000, false); if (completed) { int bytesRead = stream.EndRead(asyncReader); StringBuilder message = new StringBuilder(); message.Append(Encoding.ASCII.GetString(readBuffer, 0, bytesRead)); if (bytesRead == readBuffer.Length) { // There's possibly more than 32 bytes to read, so get the next // section of the response string continuedResponse; if (GetResponse(stream, out continuedResponse) != "") { message.Append(continuedResponse); } } response = message.ToString(); return response; } else { int bytesRead = stream.EndRead(asyncReader); if (bytesRead == 0) { // 0 bytes were returned, so the read has finished response = string.Empty; return response; } else { StringBuilder message = new StringBuilder(); message.Append(Encoding.ASCII.GetString(readBuffer, 0, bytesRead)); if (bytesRead == readBuffer.Length) { // There's possibly more than 32 bytes to read, so get the next // section of the response string continuedResponse; if (GetResponse(stream, out continuedResponse) != "") { message.Append(continuedResponse); } } response = message.ToString(); return response; } } }
private void ReadHeader(NetworkStream stream) { contextCount++; TcpClient2InputStreamContext ctx = new TcpClient2InputStreamContext(); ctx.ID = contextCount; ctx.ClientStream = stream; ctx.Header = new byte[sizeof(long)]; ctx.HeaderRead = false; stream.BeginRead(ctx.Header, 0, ctx.Header.Length, BeginReadCallback, ctx); }
public Client(TcpClient client, int clientId) { this.client = client; stream = client.GetStream(); readerBuffer = new byte[BUFFERSIZE]; writerBuffer = new byte[BUFFERSIZE]; writerStream = new MemoryStream(writerBuffer); writer = new BinaryWriter(writerStream); messages = new ConcurrentQueue<Message>(); // Hallo senden try { writer.Write((byte)MessageType.ServerHello); writer.Write((short)4); writer.Write(clientId); Flush(); Connected = true; nextMessageType = MessageType.None; nextMessageCollectedBytes = 0; nextMessageRequiredBytes = 3; stream.BeginRead(readerBuffer, nextMessageCollectedBytes, nextMessageRequiredBytes, ReadCallback, null); } catch (Exception ex) { Close(ex, false); } }
// BeginRead~ <client> private void BeginRead(TcpClient client, NetworkStream stream) { if (stream.CanRead) { try { SessionState session = new SessionState(client, stream); IAsyncResult ar = stream.BeginRead(session.buffer, 0, SessionState.BufferSize, new AsyncCallback(OnReadCallback), session); } catch (Exception e) { string msg = string.Format("BeginRead from {0} Failed => {1}", this.ToString(), e.Message); this.DoLog(ScadaDataClient, msg); // this.NotifyEvent(this, NotifyEvents.BeginRead, msg); this.OnConnectionException(e); } } }
public bool Login( string username, string password, Enums.OnlineStatus onlineStatus = Enums.OnlineStatus.Online, Enums.DeviceType deviceType = Enums.DeviceType.Android) { try { Current = this; PacketManager.InitializeHandlers(); CommandManager.InitializeCommands(); Username = username; Password = password; OnlineStatus = onlineStatus; DeviceType = deviceType; _tcpClient = new TcpClient(_host, _port); Current = this; _networkStream = _tcpClient.GetStream(); SendPacket(PacketTemplates.Logon(Username, DeviceType)); _networkStream.BeginRead(_buffer, 0, _buffer.Length, ReadCallback, null); Console.WriteLine(_buffer.Length); return true; } catch (Exception a) { return false; } }
public void ConnectToServer() { try { if(!client.Connected) { client = new TcpClient(); var attemptNum = 1; Program.BotForm.LogMessage("Connecting to host " + ConIp + ", attempt " + attemptNum + "."); while(!client.Connected) { client.Connect(ConIp, PORT); System.Threading.Thread.Sleep(250); attemptNum += 1; } if(client.Connected) { stream = client.GetStream(); //Start to read data received from the network connection. stream.BeginRead(dataBuffer, 0, dataBuffer.Length, ReceiveDataFromStream, null); Program.BotForm.LogMessage("Connected to " + ConIp + " on port " + PORT); Program.BotForm.LogMessage("Attempting to authenticate " + ConUsername + " on " + get_channel(true)); send_pass(); send_nick(); //send_data(Encoding.UTF8.GetBytes("CAP REQ :twitch.tv/membership")); //Adds IRC v3 message tags to PRIVMSG, USERSTATE, NOTICE and GLOBALUSERSTATE (if enabled with commands CAP) send_data(Encoding.UTF8.GetBytes("CAP REQ :twitch.tv/tags" + Environment.NewLine)); join_channel(); Connected = true; //Start point maker (activates every minute) giveawayPointAdder = new Timer(); giveawayPointAdder.Interval = 1000 * 60; giveawayPointAdder.Tick += Program.BotForm.AddGiveawayPoints; giveawayPointAdder.Enabled = true; send_message(Program.BotForm.txtWelcomeMessage.Text); } } else { Disconnect(); } } catch(Exception ex) { Program.BotForm.LogMessage("An error has occured: " + ex.ToString()); } }
protected override EventWaitHandle DoLoopInner(NetworkStream ns, TransferState ts) { byte[] bufferread = new byte[1024*1]; byte[] bufferwrite =null; int count; ManualResetEvent mreDone = new ManualResetEvent(false); AsyncCallback readcallback=null; readcallback = ar_c => { try { count = ns.EndRead(ar_c); ts.AddReadBytes(count); #if VERBOSE //if (ts.totalreadbytes % 10000 == 0) ConsoleLogger.LogMessage("read: " + ts.totalreadbytes); #endif bool EOFPresent = false; if (count > 0) { EOFPresent = HandleBuffer(bufferread, count, answer, out bufferwrite); ns.Write(bufferwrite, 0, bufferwrite.Length); if (bufferwrite != null) { ts.AddWriteBytes(bufferwrite.Length); } } if (EOFPresent == false && count>0) { ns.BeginRead(bufferread, 0, bufferread.Length, readcallback, ts); } else { mreDone.Set(); } } catch (IOException ioe) { if (ioe.InnerException != null) { SocketException se = ioe.InnerException as SocketException; if (se != null) { if (se.SocketErrorCode == SocketError.ConnectionReset) { ConsoleLogger.LogMessage("Client closed connection!"); mreDone.Set(); return; } } ObjectDisposedException ode = ioe.InnerException as ObjectDisposedException; if (ode != null) { ConsoleLogger.LogMessage("Client closed connection."); mreDone.Set(); return; } } throw ioe; } catch (Exception ex) { ConsoleLogger.LogMessage("Error in readcallback: " + ex.ToString()); mreDone.Set(); } }; //начинаем асинхронное чтение данных ns.BeginRead(bufferread, 0, bufferread.Length, readcallback, ts); //ожидаем завершения обработки mreDone.WaitOne(); //обработка завершена ConsoleLogger.LogMessage("Thread shutdown!"); return mreDone; }
// # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # private bool Connect() { try { TCPClient = new TcpClient(IPAddress, PortNumber); } catch ( Exception exp ) { Console.WriteLine("Can't connect: " + exp.Message); return false; } String ConnResult = ""; try { TCPStream = TCPClient.GetStream(); byte[] StreamTest = new byte[10]; IAsyncResult NetStreamReadRes = TCPStream.BeginRead(StreamTest, 0, StreamTest.Length, null, null); if ( NetStreamReadRes.AsyncWaitHandle.WaitOne(3000, false) ) { int streamLength = TCPStream.EndRead(NetStreamReadRes); NetStreamReadRes = null; ConnResult = Encoding.GetEncoding(1251).GetString(StreamTest, 0, streamLength); } else { System.Diagnostics.Trace.WriteLine("Не получил ответа о сервере"); } } catch ( Exception exp ) { Console.WriteLine("Can't create the network stream: " + exp.Message); return false; } if ( ConnResult != "$M$_$ERVER" ) return false; SetConnectionStatus(true); // Запуск пинга сервера //PingAgent = new CallTimer(PingServer, 500); Console.WriteLine("Соединение установлено"); return true; }
private bool Connect() { try { TCPClient = new TcpClient(IPAddress, PortNumber); } catch (Exception exc) { Console.WriteLine("Can't connect: " + exc.Message); return false; } String ConnResult = ""; try { TCPStream = TCPClient.GetStream(); byte[] StreamTest = new byte[10]; IAsyncResult NetStreamReadRes = TCPStream.BeginRead(StreamTest, 0, StreamTest.Length, null, null); if (NetStreamReadRes.AsyncWaitHandle.WaitOne(1500, false)) { int streamLength = TCPStream.EndRead(NetStreamReadRes); ConnResult = Encoding.GetEncoding(1251).GetString(StreamTest, 0, streamLength); } } catch (Exception exc) { Console.WriteLine("Can't create the network stream: " + exc.Message); return false; } if (ConnResult != "$M$_$ERVER") return false; SetConnectionStatus(true); if (Client.User != 0) { PackageViaWireless Package = new PackageViaWireless(0, true); Package.DefineQueryAndParams("ConnectionRecovery", ""); Package.ClientCode = Client.User; SendPackage(Package.GetPackage()); } // Запуск пинга сервера //PingAgent = new CallTimer(PingServer, 500); return true; }
private void ReadHeader(NetworkStream stream) { lock (stream) { TcpClient2InputStreamContext ctx = new TcpClient2InputStreamContext(); ctx.ClientStream = stream; ctx.Header = new byte[sizeof(long) + sizeof(int)]; ctx.HeaderRead = false; stream.BeginRead(ctx.Header, 0, ctx.Header.Length, BeginReadCallback, ctx); } }
/// <summary> /// Connects to TA server and resets internal data /// </summary> /// <param name="host">server host</param> /// <param name="port">server port</param> public void Connect(string host, int port) { tcp = new TcpClient(host, port); stream = tcp.GetStream(); readBuffer = new byte[tcp.ReceiveBufferSize]; readPosition = 0; stream.BeginRead(readBuffer, 0, readBuffer.Length, new AsyncCallback(DataRecieveCallback), this); }
private int Read(NetworkStream stream, byte[] buffer, int count) { var ar = stream.BeginRead(buffer, 0, count, null, null); if (!ar.AsyncWaitHandle.WaitOne(SocksTimeout)) { throw new SocksException("The proxy did not respond in a timely manner."); } count = stream.EndRead(ar); if (count < 2) { throw new SocksException("Unable to negotiate with the proxy."); } return count; }
protected virtual void ConnectComplete(IAsyncResult result) { Socket.EndConnect(result); NetworkStream = new NetworkStream(Socket); if(UseSSL) { NetworkStream = IgnoreInvalidSSL ? new SslStream(NetworkStream, false, (sender, certificate, chain, policyErrors) => true) : new SslStream(NetworkStream); ((SslStream)NetworkStream).AuthenticateAsClient(ServerHostname); } NetworkStream.BeginRead(ReadBuffer, ReadBufferIndex, ReadBuffer.Length, DataReceived, null); if(!string.IsNullOrEmpty(User.Password)) SendRawMessage("PASS {0}", User.Password); SendRawMessage("NICK {0}", User.Nick); SendRawMessage("USER {0} hostname servername :{1}", User.User, User.RealName); PingTimer.Start(); }
/// <summary> /// Connect to Broker /// </summary> /// <param name="host"></param> /// <param name="port"></param> public void Connect(string host, int port) { try { m_Client.Connect(host, port); m_Stream = m_Client.GetStream(); //Login var message = new Message(); message.Type = MessageType.ClientLogin; message.Source = this.Name; message.Target = string.Empty; message.WriteTo(m_Stream); //Begin reading var lengthBytes = new byte[4]; m_Stream.BeginRead(lengthBytes, 0, lengthBytes.Length, new AsyncCallback(ReadCallback), lengthBytes); } catch { } }
public HttpWebServerRequest(NetworkStream stream) { Stream = stream; RecievedPacket = new byte[4096]; Stream.BeginRead(RecievedPacket, 0, RecievedPacket.Length, ReadWebRequests, null); }
private void OnReadFromTcp(IAsyncResult ar) { int read = 0; try { read = m_tcpStream.EndRead(ar); } catch (Exception) { OnPipeDead(EventArgs.Empty); return; } if (0 == read) { OnPipeDead(EventArgs.Empty); return; } if (read != m_tcpBuffer.Length) { throw new SipProxyException("Unexpected length of header read from TCP."); } bool sip = true, rtp = true; for (byte i = 0; i < g_TcpSipPacketTag.Length; i++) { sip = sip && (m_tcpBuffer[i] == g_TcpSipPacketTag[i]); rtp = rtp && (m_tcpBuffer[i] == g_TcpRtpPacketTag[i]); } if (sip == rtp) { throw new SipProxyException("Unrecognized packet read from TCP."); } ushort dataLen = BitConverter.ToUInt16(m_tcpBuffer, g_TcpSipPacketTag.Length); byte[] myBuff = new byte[dataLen]; int readTotal = 0; while (readTotal < dataLen) { read = m_tcpStream.Read(myBuff, readTotal, myBuff.Length - readTotal); readTotal += read; } if (sip) { OnSipReceivedFromTcp( new SipMessageEventArgs(g_Ascii.GetString(myBuff, 0, myBuff.Length)) ); } else { OnRtpReceivedFromTcp( new RtpMessageEventArgs(myBuff) ); } try { m_tcpStream.BeginRead(m_tcpBuffer, 0, m_tcpBuffer.Length, OnReadFromTcp, null); } catch (Exception) { OnPipeDead(EventArgs.Empty); } }
public void GameListenerCallback(IAsyncResult ar) { TcpListener gameListener = (TcpListener)ar.AsyncState; socket = gameListener.EndAcceptSocket(ar); stream = new NetworkStream(socket); SendConnectionPacket(); stream.BeginRead(inMessage.Buffer, 0, 2, new AsyncCallback(ClientReadFirstCallBack), null); }
public static Message Read(NetworkStream stream, int timeout) { Message message = null; try { //Read length of the message var lengthBytes = new byte[4]; var asyncResult = stream.BeginRead(lengthBytes, 0, lengthBytes.Length, null, null); //Wait for result or timeout asyncResult.AsyncWaitHandle.WaitOne(timeout); if(asyncResult.IsCompleted) { int alreadyRead = stream.EndRead(asyncResult); message = Read(stream, lengthBytes, alreadyRead); } } catch { } return message; }
/// <summary> /// Initializes the connection through the man-in-the-middle server /// </summary> /// <param name="Client">A stream to the client</param> /// <param name="Server">A stream to the server</param> /// <param name="Ip">The ip of the connected player</param> public MITMMessageHandler(NetworkStream Client, NetworkStream Server, string Ip) { try { Connected = true; client = Client; server = Server; this.IP = Ip; ClientIdentified = false; client.BeginRead(packageIntReceiveBuffer, 0, IntSize, new AsyncCallback(ClientIDReceivedCallback), null); server.BeginRead(serverReceiveBuffer, 0, BUFFERSIZE, new AsyncCallback(ServerReceivedCallback), null); } catch (Exception ex) { Disconnect(); logError(ex); } }