public ConnectStage(System.Net.Sockets.Socket socket, string ipaddress, int port) { // TODO: Complete member initialization this._Socket = socket; this._Ipaddress = ipaddress; this._Port = port; }
public void Connect(string surrogatehost) { System.Net.Sockets.Socket sock = new System.Net.Sockets.Socket(System.Net.Sockets.AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Stream, System.Net.Sockets.ProtocolType.Tcp); try { sock.Connect(surrogatehost, 55905); netstm = new XNetworkStream(sock); netstm.WriteByte(199); if (netstm.ReadByte() != 199 / 3) { throw new Exception("DFS protocol did not respond correctly to handshake"); } } catch { if (netstm != null) { netstm.Close(); netstm = null; } sock.Close(); sock = null; throw; } buf = new byte[1024 * 4]; }
protected static Mono.Unix.UnixEndPoint CreateEndPoint (string path) { if (path == null) throw new ArgumentNullException ("path"); Mono.Unix.UnixEndPoint ep = new Mono.Unix.UnixEndPoint ( path); if (System.IO.File.Exists (path)) { System.Net.Sockets.Socket conn = new System.Net.Sockets.Socket ( System.Net.Sockets.AddressFamily.Unix, System.Net.Sockets.SocketType.Stream, System.Net.Sockets.ProtocolType.IP); try { conn.Connect (ep); conn.Close (); throw new InvalidOperationException ( string.Format (CultureInfo.CurrentCulture, Strings.UnixSocket_AlreadyExists, path)); } catch (System.Net.Sockets.SocketException) { } System.IO.File.Delete (path); } return ep; }
static void Main(string[] args) { string adres; int port; Console.WriteLine("PROGRAM KTORY DLA PODANEGO SERWISU WWW\nSPRAWDZA OTWARTOSC WYZNACZONEGO PORTU\n"); Console.WriteLine("Wpisz nazwe serwisu: "); adres = Console.ReadLine(); Console.WriteLine("\n"); Console.WriteLine("Wpisz numer portu: "); port = int.Parse(Console.ReadLine()); Console.WriteLine("\n"); IPHostEntry adresWWW = Dns.GetHostEntry(adres); IPAddress adresIP = adresWWW.AddressList[0]; System.Net.Sockets.Socket socket = new System.Net.Sockets.Socket(System.Net.Sockets.AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Stream, System.Net.Sockets.ProtocolType.Tcp); try { socket.Connect(adresIP, port); if (socket.Connected == true) Console.WriteLine("Port " + port + " jest otwarty"); } catch (Exception) { Console.WriteLine("Port " + port + " jest zamkniety"); } finally { socket.Close(); Console.WriteLine("\nPo nacisnieciu dowolnego klawisza program zostanie zamkniety"); } Console.ReadKey(); }
public void ScanPort() { int i; for (i = Convert.ToInt32(numStart.Value.ToString()); i <= numEnd.Value; i++) { Scanner.Text = "Scanner: Scanning Port: " + i; Port = i; System.Net.IPAddress ip = System.Net.Dns.GetHostEntry(textBox1.Text).AddressList[0]; //Gets main IP of host. IPEndPoint ipEnd = new IPEndPoint(ip, i); //Creates a new socket. System.Net.Sockets.Socket _Sock = new System.Net.Sockets.Socket(System.Net.Sockets.AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Stream, System.Net.Sockets.ProtocolType.Tcp); try //Tests the port by trying to connect. { _Sock.Connect(ipEnd); } catch //Catches the error if it can not connect. { } if (_Sock.Connected == true) //Checks if socket is connected. { Invoke(new AddDelegate(AddOpen), Port.ToString()); } else { Invoke(new ClosedDelegate(AddClosed), Port.ToString()); } _Sock.Close(); //Closes the socket once complete. } Invoke(new Finished(Done)); }
public StandardSocket(System.Net.Sockets.Socket socket) { if (socket == null) throw new ArgumentNullException ("socket"); this.socket = socket; }
public static CriticalSection Create(string lockname) { if (null == lockname) { if (currentSection != null) { return currentSection; } } else { if (0 == lockname.Length) { throw new Exception("Empty lock name is invalid"); } } System.Net.Sockets.Socket sock = new System.Net.Sockets.Socket(System.Net.Sockets.AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Stream, System.Net.Sockets.ProtocolType.Tcp); System.Net.Sockets.NetworkStream ntsm = null; try { ////sock.Connect(Surrogate.MasterHost, 55900); sock.Connect(DO5_Surrogate_LocateMasterHost(".."), 55900); ntsm = new XNetworkStream(sock); ntsm.WriteByte((byte)'J'); //hand shake with surrogate if (ntsm.ReadByte() == (byte)'+') { CriticalSection sec = new CriticalSection(); sec.sock = sock; sec.ntsm = ntsm; sec.hasLock = false; if (null == lockname) { currentSection = sec; } else { sec.locknamebytes = Encoding.UTF8.GetBytes(lockname); } return sec; } else { throw new Exception("CriticalSection.Create() handshake failed."); } } catch { if (ntsm != null) { ntsm.Close(); ntsm = null; } sock.Close(); sock = null; throw; } }
public Socket(String host, int port) { System.Net.IPHostEntry hostEntry = System.Net.Dns.GetHostEntry (host); System.Net.IPAddress serverIP = hostEntry.AddressList [0]; System.Net.IPEndPoint serverEP = new System.Net.IPEndPoint(serverIP,port); this.delegateInstance = new System.Net.Sockets.Socket(System.Net.Sockets.AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Stream, System.Net.Sockets.ProtocolType.Tcp); }
/// <summary> /// Constructor to specify the socket parameters. /// </summary> /// <param name="socketAddressFamily"></param> /// <param name="socketType"></param> /// <param name="socketProtocolType"></param> public TwoSensesSocket(System.Net.Sockets.AddressFamily socketAddressFamily, System.Net.Sockets.SocketType socketType, System.Net.Sockets.ProtocolType socketProtocolType) { // Subscribe for receiving data. p_socketReceiveEventArgs.Completed += new EventHandler<System.Net.Sockets.SocketAsyncEventArgs>(SocketReceiveEventArgs_Completed); // Subscribe for sending data. // p_socketSendEventArgs.Completed += new EventHandler<System.Net.Sockets.SocketAsyncEventArgs>(SocketSendEventArgs_Completed); // Initialize the socket. p_twoSensesSocket = new System.Net.Sockets.Socket(socketAddressFamily, socketType, socketProtocolType); }
public Peer(System.Net.Sockets.Socket client) { _Socket = client; _SoulProvider = new Remoting.Soul.SoulProvider(this, this); _Responses = new Queue<Remoting.Package>(); _Requests = new Queue<Request>(); _ReadMachine = new Game.StageMachine(); _WriteMachine = new Game.StageMachine(); _Enable = true; }
public override void Disconnect() { if (Socket != null) { Console.WriteLine("Telnet client left gracefully : " + Socket.RemoteEndPoint.ToString()); Socket.Close(); Socket = null; //if (!WasRejected) Mud.ClientDisconnected(this); } }
static void ListenThreadProc() { bool keepgoing = true; while (keepgoing) { try { if (lsock != null) { lsock.Close(); } lsock = new System.Net.Sockets.Socket(System.Net.Sockets.AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Stream, System.Net.Sockets.ProtocolType.Tcp); System.Net.IPEndPoint ipep = new System.Net.IPEndPoint(System.Net.IPAddress.Any, 55905); for (int i = 0; ; i++) { try { lsock.Bind(ipep); break; } catch { if (i >= 5) { throw; } System.Threading.Thread.Sleep(1000 * 4); continue; } } lsock.Listen(30); for (; ; ) { System.Net.Sockets.Socket dllclientSock = lsock.Accept(); DfsProtocolClientHandler ch = new DfsProtocolClientHandler(); System.Threading.Thread cthd = new System.Threading.Thread(new System.Threading.ParameterizedThreadStart(ch.ClientThreadProc)); cthd.IsBackground = true; cthd.Start(dllclientSock); } } catch (System.Threading.ThreadAbortException e) { keepgoing = false; } catch (Exception e) { XLog.errorlog("DfsProtocol.ListenThreadProc exception: " + e.ToString()); } } }
static void Main(string[] args) { if (System.IO.File.Exists(conffile)) { string[] conflines = System.IO.File.ReadAllLines(conffile); foreach (string confline in conflines) { if (confline.Split('|')[0] == "minutesbetweenpost" && confline.Split('|')[0].Length > 1) int.TryParse(confline.Split('|')[1], out minutesbetweenpost); } } else System.IO.File.WriteAllText(conffile, "minutesbetweenpost|" + minutesbetweenpost.ToString()); //Below was for the first auth with twitter. /*Twitterizer.OAuthTokenResponse otokenresp = Twitterizer.OAuthUtility.GetRequestToken("s4NnGFjXHow8E4sAghj2cA", "J75EVo7fFnRIOyWvWAMv1cj2oIPEJq73CIsULO0k", "oob"); Console.WriteLine("http://twitter.com/oauth/authorize?oauth_token=" + otokenresp.Token); Console.WriteLine("Hit enter when done."); Console.Read(); Console.Write("Enter the pin: "); string pin = Console.ReadLine(); Twitterizer.OAuthTokenResponse otokenrespverified = Twitterizer.OAuthUtility.GetAccessToken("s4NnGFjXHow8E4sAghj2cA", "J75EVo7fFnRIOyWvWAMv1cj2oIPEJq73CIsULO0k", otokenresp.Token, pin); Console.WriteLine("Got the following data:\nScreenname: {0}\nToken: {1}\nToken secret: {2}", otokenrespverified.ScreenName, otokenrespverified.Token, otokenrespverified.TokenSecret); Console.ReadLine(); */ Twitterizer.OAuthTokens otokens = new Twitterizer.OAuthTokens(); otokens.ConsumerKey = "s4NnGFjXHow8E4sAghj2cA"; otokens.ConsumerSecret = "J75EVo7fFnRIOyWvWAMv1cj2oIPEJq73CIsULO0k"; otokens.AccessToken = "407275798-F3Jp52bV8YYnQdXkvt9CyfnbgSG5eqm3fWuvKPnV"; otokens.AccessTokenSecret = "WQcWvYms6QU4jwVOEwzJl0PDAoBxIZaYkL6q5c6Fxc"; //Twitterizer.TwitterResponse<Twitterizer.TwitterUser> showusreresp = Twitterizer.TwitterUser.Show(otokens, "Onymity"); //Console.WriteLine(showusreresp.Result); while (true) { System.Net.Sockets.Socket bacon = new System.Net.Sockets.Socket(System.Net.Sockets.AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Stream, System.Net.Sockets.ProtocolType.Tcp); bacon.Connect("localhost", 5000); CedLib.Networking.socketfunctions.sendstring(bacon, "talk"); CedLib.Networking.socketfunctions.waitfordata(bacon, 1000, false); string botsays = CedLib.Networking.socketfunctions.receivestring(bacon, false); logger.log("Posting: " + botsays, CedLib.Logging.Priority.Notice); Console.WriteLine(Twitterizer.TwitterStatus.Update(otokens, "Bot says: " + botsays).Result); System.Threading.Thread.Sleep(minutesbetweenpost * 60000); if (System.IO.File.Exists(conffile)) { string[] conflines = System.IO.File.ReadAllLines(conffile); foreach (string confline in conflines) { if (confline.Split('|')[0] == "minutesbetweenpost" && confline.Split('|')[0].Length > 1) int.TryParse(confline.Split('|')[1], out minutesbetweenpost); } } else System.IO.File.WriteAllText(conffile, "minutesbetweenpost|" + minutesbetweenpost.ToString()); } }
internal DataAsyncState(int bufferSize, System.Net.Sockets.Socket client, string dataBuffer, int recievedBytes, int totalBytes, string prevData, int index) { mData = new byte[bufferSize]; mClient = client; mBuffer = dataBuffer; mRecievedBytes = recievedBytes; mTotalBytes = totalBytes; mPrevData = prevData; mCompleted = false; mIndex = index; }
public StandardSocket(System.Net.Sockets.AddressFamily addressFamily, System.Net.Sockets.SocketType socketType, System.Net.Sockets.ProtocolType protocolType, System.Net.EndPoint localEndPoint) { if (localEndPoint == null) throw new ArgumentNullException ("localEndPoint"); socket = new System.Net.Sockets.Socket (addressFamily, socketType, protocolType); this.localEndPoint = localEndPoint; }
internal DataAsyncState(int bufferSize, System.Net.Sockets.Socket client, int index) { mData = new byte[bufferSize]; mClient = client; mBuffer = ""; mRecievedBytes = 0; mTotalBytes = -1; mPrevData = ""; mCompleted = false; mResult = null; mIndex = index; }
public void Close() { if (socket != null) { if (_state == 1) _state=2; socket.Shutdown(System.Net.Sockets.SocketShutdown.Both); socket.Close(); socket = null; } }
protected SocketSession(IoService service, IoProcessor processor, IoSessionConfig config, System.Net.Sockets.Socket socket, EndPoint localEP, EndPoint remoteEP, Boolean reuseBuffer) : base(service) { _socket = socket; _localEP = localEP; _remoteEP = remoteEP; Config = config; if (service.SessionConfig != null) Config.SetAll(service.SessionConfig); _processor = processor; _filterChain = new DefaultIoFilterChain(this); }
public void Listen() { ListenSocket = new System.Net.Sockets.Socket( System.Net.Sockets.AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Stream, System.Net.Sockets.ProtocolType.IP); ListenSocket.Bind(new System.Net.IPEndPoint(0, Port)); ListenSocket.Listen(16); ListenSocket.BeginAccept(OnNewClient, null); Console.WriteLine("Listening on port " + Port); }
public static void Execute(IPEndPoint IPEndPoint, byte[] command) { _socket = new System.Net.Sockets.Socket( System.Net.Sockets.AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Stream, System.Net.Sockets.ProtocolType.Tcp); var arg = new System.Net.Sockets.SocketAsyncEventArgs() { RemoteEndPoint = IPEndPoint }; arg.SetBuffer(command, 0, command.Length); arg.Completed += Sending_Completed; var result = _socket.ConnectAsync(arg); //socket.SendToAsync(arg); }
/// <summary> /// 连接到服务器,如果连接失败,则会抛出异常。 /// </summary> public void Connect() { closeSocket(); if (socket == null) { socket = new System.Net.Sockets.Socket(System.Net.Sockets.AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Stream, System.Net.Sockets.ProtocolType.Tcp); } socket.Connect(hostname, port); // 开始接收数据 (new Thread(startReceive)).Start(); if (AutoRequestEncryption) RequestEncryption(); }
private static void Connect() { try { Byte[] byteRecv = new Byte[32769]; int recvBytes = 0; _socket = new System.Net.Sockets.Socket(System.Net.Sockets.AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Stream, System.Net.Sockets.ProtocolType.Tcp); try { Logging.Trace("Connecting to {0}:{1}", Logging.LogLevel.Info, _currentService.IP, _currentService.Port); _socket.Connect(_currentService.IP, _currentService.Port); } catch { Logging.Trace("Could not connect to server. Type 'relog' to reconnect.", Logging.LogLevel.Error); return; } Logging.Trace("Connected.", Logging.LogLevel.Debug); Thread senderThread = new Thread(Sending); senderThread.Start(); Thread parseThread = new Thread(ParsePackets); parseThread.Start(); do { while (_socket.Available == 0) Thread.Sleep(0); recvBytes = _socket.Receive(byteRecv, System.Net.Sockets.SocketFlags.None); if (recvBytes == 0) break; _buffer.Append(byteRecv, recvBytes); } while (true); } catch { } finally { } }
public bool Connect(string addr, int port) { if (_state == 1) return false; // IPHostEntry hostEntry = null; // Get host related information. // hostEntry = Dns.GetHostEntry(addr); // Loop through the AddressList to obtain the supported AddressFamily. This is to avoid // an exception that occurs when the host IP Address is not compatible with the address family // (typical in the IPv6 case). // foreach(IPAddress address in hostEntry.AddressList) // { System.Net.IPAddress address = System.Net.IPAddress.Parse(addr); System.Net.IPEndPoint ipe = new System.Net.IPEndPoint(address, port); System.Net.Sockets.Socket tempSocket = new System.Net.Sockets.Socket(ipe.AddressFamily, System.Net.Sockets.SocketType.Stream, System.Net.Sockets.ProtocolType.Tcp); tempSocket.Connect(ipe); if(tempSocket.Connected) { // Disable the Nagle Algorithm for this tcp socket. tempSocket.NoDelay = true; _state = 1; socket = tempSocket; return true; } // else // { // continue; // } // } _state = 0; socket = null; return false; }
static string GetLocalIPAddress(IPAddress address) { try { HFTLog.Global.Info("Trying: " + address.ToString()); string localIP; using (System.Net.Sockets.Socket socket = new System.Net.Sockets.Socket(address.AddressFamily, System.Net.Sockets.SocketType.Dgram, 0)) { socket.Connect(address, 65530); IPEndPoint endPoint = socket.LocalEndPoint as IPEndPoint; localIP = endPoint.Address.ToString(); } return localIP; } catch (System.Exception ex) { HFTLog.Global.Info(ex.ToString()); return null; } }
public void Connect(System.String HostName) { //prntSome.printSome("Connect"); System.Int32 port = 10012; System.Net.IPAddress addrRdb; System.Net.IPAddress[] addr = new System.Net.IPAddress[1]; if (System.Net.IPAddress.TryParse(HostName, out addrRdb)) { //must do push ip to array here } else { //System.Net.IPHostEntry IPHost = System.Net.Dns.GetHostEntry(HostName); //System.Net.IPAddress[] addr = IPHost.AddressList; } addr[0] = addrRdb; try { this.runOffline = false; // Create New Socket this.CurSocket = new System.Net.Sockets.Socket ( System.Net.Sockets.AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Stream, System.Net.Sockets.ProtocolType.Tcp); // Create New EndPoint System.Net.IPEndPoint iep = new System.Net.IPEndPoint(addr[0],port); // This is a non blocking IO this.CurSocket.Blocking = false ; // Begin Asyncronous Connection this.CurSocket.BeginConnect (iep, new System.AsyncCallback (ConnectCallback), CurSocket) ; } catch (System.Exception CurException) { this.runOffline = true; System.Console.WriteLine ("Connect: " + CurException.Message); } }
public static bool Send(String servidorstr, int puerto, string datos) { bool result = false; try { IPAddress servidor = IPAddress.Parse(servidorstr); //string request = "<DIR>"; Byte[] bytesSent = Encoding.ASCII.GetBytes(datos); Byte[] bytesReceived = new Byte[256]; // Crear socket ip, puerto IPEndPoint ipe = new IPEndPoint(servidor, puerto); System.Net.Sockets.Socket s = new System.Net.Sockets.Socket(System.Net.Sockets.AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Stream, System.Net.Sockets.ProtocolType.Tcp); s.Connect(ipe); s.Send(bytesSent, bytesSent.Length, 0); try { byte[] data = new byte[1024]; int receivedDataLength = s.Receive(data); string stringData = Encoding.ASCII.GetString(data, 0, receivedDataLength); Console.WriteLine(stringData); s.Shutdown(System.Net.Sockets.SocketShutdown.Both); s.Close(); result = true; } catch (Exception e) { Console.WriteLine(e.StackTrace); } } catch (Exception se) { Console.WriteLine("Error en conexión" + se.StackTrace); } return result; }
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) { try { Tuple<string, uint, string> req = (Tuple<string, uint, string>)e.Argument; for (uint i = 0; i < req.Item2; ++i) { if(e.Cancel) break; System.Net.Sockets.Socket s = new System.Net.Sockets.Socket(System.Net.Sockets.AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Stream, System.Net.Sockets.ProtocolType.Tcp); s.Connect("localhost", 5124); System.Net.Sockets.NetworkStream ns = new System.Net.Sockets.NetworkStream(s); System.IO.StreamWriter sw = new System.IO.StreamWriter(ns); System.IO.StreamReader r = new System.IO.StreamReader(ns); sw.Write(req.Item1); sw.Flush(); backgroundWorker1.ReportProgress((int)((100 * i) / req.Item2), FormatResponse(r.ReadToEnd(), req.Item3)); } } catch (Exception ex) { e.Result = ex.ToString(); return; } }
public bool CheckConnection() { if (serverSocket != null) { if (serverSocket.Pending() == true) { //Accept the pending client connection and return a TcpClient object initialized for communication. clientSocket = serverSocket.AcceptSocket(); // Disable the Nagle Algorithm for this tcp socket. clientSocket.NoDelay = true; // Using the RemoteEndPoint property. //Console.WriteLine("I am listening for connections on " + // IPAddress.Parse(((IPEndPoint)tcpListener.LocalEndpoint).Address.ToString()) + // "on port number " + ((IPEndPoint)tcpListener.LocalEndpoint).Port.ToString()); return true; } } return false; }
protected SocketSenderReceiverBase(System.Net.Sockets.Socket socket, System.IO.Pipelines.PipeScheduler scheduler) { }
public static bool CanRead(this System.Net.Sockets.Socket socket, int microSeconds = 0) { return(Poll(socket, System.Net.Sockets.SelectMode.SelectRead, microSeconds)); }
static void Main(string[] args) { OverflowExample(); //Big Integer BigInteger bigIntFromDouble = new BigInteger(4564564564542332); BigInteger assignedFromDouble = (BigInteger)4564564564542332; //Sorted set SortedSet <int> MySortedSet = new SortedSet <int> { 8, 2, 1, 5, 10, 5, 10, 8 }; //Tuple Tuple <int, int, int, int, int> MultiplesOfTwo = Tuple.Create(2, 4, 6, 8, 10); Console.WriteLine(MultiplesOfTwo.Item2); var multiples = new Tuple <int, int, int, int, int, int, int, Tuple <int, int, int> >(2, 4, 6, 8, 10, 12, 14, new Tuple <int, int, int>(3, 6, 9)); Console.WriteLine(multiples.Rest.Item1); //Complex number Complex c1 = new Complex(8, 2); Complex c2 = new Complex(8, 2); Complex c3 = c1 + c2; //File.ReadLines IEnumerable <string> FileContent = File.ReadLines("MyFile.txt"); foreach (string Line in FileContent) { Console.Write(Line); } //Memory stream MemoryStream destinationStream = new MemoryStream(); using (FileStream sourceStream = File.Open(@"c:\temp.txt", FileMode.Open)) { sourceStream.CopyTo(destinationStream); } //Try parse Guid myGuid; Guid.TryParse("not a guid", out myGuid); //Enum example CarOptions myCar = CarOptions.MP3Player | CarOptions.AirCon | CarOptions.Turbo; Console.WriteLine("Does car have MP3? {0}", myCar.HasFlag(CarOptions.MP3Player)); Console.ReadKey(); //IsNullOrWhiteSpace String.IsNullOrWhiteSpace(" "); //Clear StringBuilder sb = new StringBuilder("long string"); sb.Clear(); //Special folder additions var test = Environment.SpecialFolder.CDBurning; //64 bit changes Console.WriteLine(Environment.Is64BitOperatingSystem); Console.WriteLine(Environment.Is64BitProcess); //stopwatch var sw = new Stopwatch(); sw.Start(); //httpwebrequest string loadbalancerIp = "http://127.0.0.1/"; string host = "mywebsite.com"; var request = WebRequest.Create("http://127.0.0.1/") as HttpWebRequest; var socket = new System.Net.Sockets.Socket(new System.Net.Sockets.SocketInformation()); socket.Connect(new DnsEndPoint("www.microsoft.com", 80)); request.Date = System.DateTime.Now; sw.Restart(); }
void P2ServerReceiveHander(byte command, string data, System.Net.Sockets.Socket soc) { try { if (command == 0xff) { WeaveExcCmdNoCheckCmdName(command, data, soc); try { string[] temp = data.Split('|'); if (temp[0] == "in") { //加入onlinetoken WeaveOnLine ol = new WeaveOnLine(); ol.Token = temp[1]; ol.Socket = soc; weaveOnline.Add(ol); foreach (CmdWorkItem CI in CmdWorkItems) { try { CI.WeaveTcpCmd.TokenIn(ol); } catch (Exception ex) { WeaveLogEvent?.Invoke("Tokenin", ex.Message); } } return; } else if (temp[0] == "Restart") { int count = weaveOnline.Count; WeaveOnLine[] ols = new WeaveOnLine[count]; weaveOnline.CopyTo(0, ols, 0, count); string IPport = ((System.Net.IPEndPoint)soc.RemoteEndPoint).Address.ToString() + ":" + temp[1]; foreach (WeaveOnLine ol in ols) { try { if (ol.Socket != null) { String IP = ((System.Net.IPEndPoint)ol.Socket.RemoteEndPoint).Address.ToString() + ":" + ((System.Net.IPEndPoint)ol.Socket.RemoteEndPoint).Port; if (IP == IPport) { ol.Socket = soc; } } } catch { } } } else if (temp[0] == "out") { ////移出onlinetoken int count = weaveOnline.Count; WeaveOnLine[] ols = new WeaveOnLine[count]; weaveOnline.CopyTo(0, ols, 0, count); foreach (WeaveOnLine onlinesession in ols) { if (onlinesession.Token == temp[1]) { foreach (CmdWorkItem cmdItem in CmdWorkItems) { try { cmdItem.WeaveTcpCmd.Tokenout(onlinesession); } catch (Exception ex) { WeaveLogEvent?.Invoke("Tokenout", ex.Message); } } weaveOnline.Remove(onlinesession); return; } } } } catch { } return; } else { WeaveExcCmd(command, data, soc); } } catch { return; } //System.Threading.ThreadPool.QueueUserWorkItem(new System.Threading.WaitCallback(exec)); }
public static int ProbeForOpenPort(System.Net.Sockets.ProtocolType type, int start = 30000, bool even = true, System.Net.IPAddress localIp = null) { if (localIp == null) { localIp = GetFirstUnicastIPAddress(System.Net.Sockets.AddressFamily.InterNetwork); // System.Net.IPAddress.Any should give unused ports across all IP's? } System.Net.Sockets.Socket working = null; //Switch on the type switch (type) { //Handle TCP case System.Net.Sockets.ProtocolType.Tcp: { working = new System.Net.Sockets.Socket(localIp.AddressFamily, System.Net.Sockets.SocketType.Stream, type); Media.Common.Extensions.Socket.SocketExtensions.DisableAddressReuse(working); break; } //Handle UDP case System.Net.Sockets.ProtocolType.Udp: { working = new System.Net.Sockets.Socket(localIp.AddressFamily, System.Net.Sockets.SocketType.Dgram, type); Media.Common.Extensions.Socket.SocketExtensions.DisableAddressReuse(working); break; } //Don't handle default: return(-1); } //The port is in the valid range. using (working) while (start <= ushort.MaxValue) { try { //Try to bind the end point. working.Bind(new System.Net.IPEndPoint(localIp, start)); //We are done if we can bind. break; } catch (System.Exception ex) { //Check for the expected error. if (ex is System.Net.Sockets.SocketException) { System.Net.Sockets.SocketException se = (System.Net.Sockets.SocketException)ex; if (se.SocketErrorCode == System.Net.Sockets.SocketError.AddressAlreadyInUse) { //Try next port if (++start > ushort.MaxValue) { //No port found start = -1; break; } //Ensure even if possible if (even && Common.Binary.IsOdd(ref start) && start < ushort.MaxValue) { ++start; } //Iterate again continue; } } //Something bad happened start = -1; break; } } //Return the port. return(start); }
/// <summary> /// Connection worker thread - checks if server is available /// if server is available it sets the flag and starts polling for configuration injects /// if not it unset the flag and trying again sleeping given time /// </summary> private void ConnectionThreadWorker() { //Environment.SpecialFolder. Console.WriteLine(ip + ":" + port); eventLog1.WriteEntry("Connection Worker started...", EventLogEntryType.Information); System.Net.IPAddress ipAddress = System.Net.IPAddress.Parse(ip); System.Net.IPEndPoint remoteEP = new System.Net.IPEndPoint(ipAddress, port); this.sockfd = null; //this.sockfd = new System.Net.Sockets.Socket(System.Net.Sockets.AddressFamily.InterNetwork, // System.Net.Sockets.SocketType.Stream, System.Net.Sockets.ProtocolType.Tcp); bool before = true; while (true) { if (!IsSocketConnected(this.sockfd, before)) { isConnected = false; try { #if (DEBUG) Console.WriteLine("count: " + packetList.Count); #endif this.sockfd = new System.Net.Sockets.Socket(System.Net.Sockets.AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Stream, System.Net.Sockets.ProtocolType.Tcp); this.sockfd.Connect(remoteEP); byte[] buf = new byte[3]; sockfd.ReceiveTimeout = 1000; sockfd.Receive(buf); if (buf.SequenceEqual(new byte[] { 0xFF, 0xFE, 0xFD })) { #if (DEBUG) Console.WriteLine("Cannot connect: Server refuses connection from this IP"); #endif return; } sockfd.ReceiveTimeout = 0; isConnected = true; before = false; #if (DEBUG) Console.WriteLine("Connected!"); #endif this.SendPacketList(packetList); } catch (Exception e) { this.sockfd = null; eventLog1.WriteEntry("Cannot connect to server. Still trying...", EventLogEntryType.Warning); #if (DEBUG) Console.WriteLine("Cannot connect to server. Still trying..."); #endif } } else { SharedClasses.ConfigPacket cp; cp = (SharedClasses.ConfigPacket)ReceiveObject(sockfd); if (cp != null) { /* * <add key="serverIP" value="127.0.0.1"/> * <add key="serverPort" value="9191"/> * <add key="folderPath" value="C:\\temp;D:\\tmp"/> <!-- enter folder paths to watch separated by semicolons ';' like: "C:\\temp;D:\\temp\\something" --> * <add key="fileFilter" value="*.java;*.c"/> <!-- enter file filters separated by semicolons ';' like: "*.c;*.cs;*.html" --> * <add key="includeSubDirs" value="true"/> <!-- true or false --> * <add key="serialNumber" value="b7337eee-d172-4cc7-a9eb-c180662aa950"/> * */ #if (DEBUG) Console.WriteLine(cp.ToString()); #endif var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); config.AppSettings.Settings["serverIP"].Value = cp.ServerIP; config.AppSettings.Settings["serverPort"].Value = cp.ServerPort; config.AppSettings.Settings["folderPath"].Value = cp.WatcherDirectories; config.AppSettings.Settings["fileFilter"].Value = cp.WatcherFilters; config.AppSettings.Settings["includeSubDirs"].Value = cp.WatcherIncludeSubdirectories; config.AppSettings.Settings["serialNumber"].Value = cp.SerialNumber; config.Save(ConfigurationSaveMode.Modified); ConfigurationManager.RefreshSection("appSettings"); //InitWatchers(); #if (DEBUG) Console.WriteLine("New configuration injected - restarting Service"); #endif eventLog1.WriteEntry("New configuration injected - restarting Service", EventLogEntryType.Information); OnStop(); Environment.Exit(1); } #if (DEBUG) Console.WriteLine("Already connected"); #endif } Thread.Sleep(1000 * 3); } //Console.WriteLine("Connection Worker ended successfully"); //this.SendPacketList(packetList); }
private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) { try { if (!IsValidate && Socket != null) { if (this.Socket.Connected) this.Socket.Shutdown(System.Net.Sockets.SocketShutdown.Both); this.Socket.Close(); this.Socket = null; if (OnClose != null) OnClose(this, null); } } catch { } timer.Enabled = false; }
public static void DisableTcpRetransmissions(System.Net.Sockets.Socket socket) { SetMaximumTcpRetransmissionTime(socket, 0); }
// Listen for data on the socket - call appropriate handlers based on first byte public void Listen(Socket socket) { int returnCode = 0; byte first = 0x00; byte[] buffer = new byte[1]; returnCode = socket.Receive(buffer, 0); if (returnCode > 0) { first = buffer[0]; switch (first >> 4) { case 0: // RESERVED Debug.Print("Done! First reserved message received."); returnCode = ERROR; break; case 1: // Connect (Broker Only) Debug.Print("Done! CONNECT message received."); returnCode = ERROR; break; case 2: // CONNACK Debug.Print("Done! CONNACK message received."); returnCode = HandleCONNACK(socket, first); break; case 3: // PUBLISH Debug.Print("Done! PUBLISH message received."); returnCode = HandlePUBLISH(socket, first); break; case 4: // PUBACK (QoS > 0 - did it anyway) Debug.Print("Done! PUBACK message received."); returnCode = HandlePUBACK(socket, first); break; case 5: // PUBREC (QoS 2) Debug.Print("Done! PUBREC message received."); returnCode = ERROR; break; case 6: // PUBREL (QoS 2) Debug.Print("Done! PUBREL message received."); returnCode = ERROR; break; case 7: // PUBCOMP (QoS 2) Debug.Print("Done! PUBCOMP message received."); returnCode = ERROR; break; case 8: // SUBSCRIBE (Broker only) Debug.Print("Done! SUBSCRIBE message received."); returnCode = ERROR; break; case 9: // SUBACK Debug.Print("Done! SUBACK message received."); returnCode = HandleSUBACK(socket, first); break; case 10: // UNSUBSCRIBE (Broker Only) Debug.Print("Done! UNSUBSCRIBE message received."); returnCode = ERROR; break; case 11: // UNSUBACK Debug.Print("Done! UNSUBACK message received."); returnCode = HandleUNSUBACK(socket, first); break; case 12: // PINGREQ (Technically a Broker Deal - but we're doing it anyway) Debug.Print("Done! PINGREQ message received."); returnCode = HandlePINGREQ(socket, first); break; case 13: // PINGRESP Debug.Print("Done! PINGRESP message received."); pingresp = true; returnCode = HandlePINGRESP(socket, first); break; case 14: // DISCONNECT (Broker Only) Debug.Print("Done! DISCONNECT message received."); returnCode = ERROR; break; case 15: // RESERVED Debug.Print("Done! Last reserved Message received."); returnCode = ERROR; break; default: // Default action Debug.Print("Done! Unknown message received."); // Should never get here returnCode = ERROR; break; } if (returnCode != SUCCESS) { Debug.Print("Error! An error occurred in message processing on <" + socket.ToString() + "> port."); } } }
public static void SetLingerOption(System.Net.Sockets.Socket socket, System.Net.Sockets.LingerOption lingerOption) { socket.SetSocketOption(System.Net.Sockets.SocketOptionLevel.Socket, System.Net.Sockets.SocketOptionName.Linger, lingerOption); }
public static void SetLingerOption(System.Net.Sockets.Socket socket, bool enable, int seconds) { SetLingerOption(socket, new System.Net.Sockets.LingerOption(enable, seconds)); }
public static bool Poll(this System.Net.Sockets.Socket socket, System.Net.Sockets.SelectMode mode, int microSeconds) { return(socket.Poll(microSeconds, mode)); }
public static void EnableLinger(System.Net.Sockets.Socket socket) { socket.SetSocketOption(System.Net.Sockets.SocketOptionLevel.Socket, System.Net.Sockets.SocketOptionName.DontLinger, false); }
public INetSession CreateSession(INetApplication application, INetProtocol protocol, INetServer server, System.Net.Sockets.Socket client) { SocketSession s = new SocketSession(application, protocol, server, client); SocketServerConfig config = null; if (server is SocketServerBase) { config = (server as SocketServerBase).Config; } if (config != null) { s.Timeout = TimeSpan.FromMinutes(config.SessionTimeout); s.TimeoutType = config.TimeoutType; } return(s); }
/// <summary> /// Return a BasicSocketClientHandler instance. /// </summary> /// <param name="handler">The socket client handler</param> /// <param name="sslStream">The ssl stream</param> /// <param name="sendHandleTimeout">The send timeout</param> /// <param name="socketSendTimeout">The socket timeout</param> /// <returns>The socket client handler</returns> protected override SocketServerLib.SocketHandler.AbstractTcpSocketClientHandler GetHandler(System.Net.Sockets.Socket handler, System.Net.Security.SslStream sslStream) { return(new AsyncClientServerLib.SocketHandler.AsyncSocketClientHandler(handler, sslStream)); }
// Unsubscribe to a topic public int UnsubscribeMQTT(Socket socket, string[] topic, int[] QoS, int topics) { int index = 0; int index2 = 0; int messageIndex = 0; int messageID = 0; int tmp = 0; int fixedHeader = 0; int varHeader = 0; int payloadLength = 0; int remainingLength = 0; int returnCode = 0; byte[] buffer = null; byte[][] utf8Topics = null; UTF8Encoding encoder = new UTF8Encoding(); utf8Topics = new byte[topics][]; while (index < topics) { utf8Topics[index] = new byte[Encoding.UTF8.GetBytes(topic[index]).Length]; utf8Topics[index] = Encoding.UTF8.GetBytes(topic[index]); if ((utf8Topics[index].Length > MAX_TOPIC_LENGTH) || (utf8Topics[index].Length < MIN_TOPIC_LENGTH)) { return(TOPIC_LENGTH_ERROR); } else { payloadLength += 2; // Size (LSB + MSB) payloadLength += utf8Topics[index].Length; // Length of topic index++; } } // Calculate the size of the fixed header fixedHeader++; // byte 1 // Calculate the size of the var header varHeader += 2; // Message ID is 2 bytes // Calculate the remaining size remainingLength = varHeader + payloadLength; // Check that remaining encoded length will fit into 4 encoded bytes if (remainingLength > MAXLENGTH) { return(MESSAGE_LENGTH_ERROR); } // Add space for each byte we need in the fixed header to store the length tmp = remainingLength; while (tmp > 0) { fixedHeader++; tmp = tmp / 128; } ; // Build buffer for message buffer = new byte[fixedHeader + varHeader + payloadLength]; // Start of Fixed header // Publish (3.3) buffer[messageIndex++] = MQTT_UNSUBSCRIBE_TYPE; // Add remaining length - writes to buffer, so need to get the new index back messageIndex = DoRemainingLength(remainingLength, messageIndex, buffer); // End Fixed Header // Start of Variable header // Message ID messageID = Rand.Next(MAX_MESSAGEID); buffer[messageIndex++] = (byte)(messageID / 256); // Length MSB buffer[messageIndex++] = (byte)(messageID % 256); // Length LSB // End of variable header // Start of Payload index = 0; while (index < topics) { // Length of Topic buffer[messageIndex++] = (byte)(utf8Topics[index].Length / 256); // Length MSB buffer[messageIndex++] = (byte)(utf8Topics[index].Length % 256); // Length LSB index2 = 0; while (index2 < utf8Topics[index].Length) { buffer[messageIndex++] = utf8Topics[index][index2]; index2++; } index++; } // End of Payload returnCode = socket.Send(buffer, buffer.Length, 0); if (returnCode < buffer.Length) { return(CONNECTION_ERROR); } return(SUCCESS); }
public SocketSender(System.Net.Sockets.Socket socket, System.IO.Pipelines.PipeScheduler scheduler) : base(default(System.Net.Sockets.Socket), default(System.IO.Pipelines.PipeScheduler)) { }
public SocketPacket(System.Net.Sockets.Socket socket, int clientNumber, string ClientIP) { m_currentSocket = socket; m_clientNumber = clientNumber; m_ClientIP = ClientIP; }
private void OnAddRead(System.Net.Sockets.Socket socket, ISocketCallback callback) { throw new System.NotSupportedException(); }
//Todo, make an IP to test and determine what options are support e.g. /MapSocketOptions. //Could also just have a SocketOptionProvider... //// SO_CONNECT_TIME = 0x700C, ////IP_MULTICAST_IF = 9, ////IPV6_MULTICAST_HOPS = 10, ////IPV6_MULTICAST_LOOP = 11 //const int JoinGroup = 41; //12 AddMembership //IPV6_ADD_MEMBERSHIP //const int LeaveGroup = 42; //13 DropMembership //IPV6_DROP_MEMBERSHIP //IPV6_LEAVE_GROUP //const int BlockSource = 43; //17 //const int UnblockSource = 44; //18 ////IP_PKTINFO = 19 ////P_HOPLIMIT = 21, IPV6_HOPLIMIT ////IP_RECEIVE_BROADCAST = 22, ////IP_RECVIF = 24, IPV6_RECVIF ////IP_IFLIST = 28, ////DontFragment = 14 //const int JoinSourceGroup = 45; // 15 (AddSourceMembership) //const int LeaveSourceGroup = 46; // 16 (DropSouceMembership) //const int Filter = 47; //MCAST_MSFILTER #endregion public static void LeaveMulticastGroup(this System.Net.Sockets.Socket socket, System.Net.IPAddress toJoin, System.Net.IPAddress sourceIp) { LeaveMulticastGroup(socket, CreateMembershipAddress(((System.Net.IPEndPoint)socket.LocalEndPoint).Address, toJoin, sourceIp)); }
// Connect to the MQTT Server public int ConnectMQTT(Socket socket, string clientID, int keepAlive = 20, bool cleanSession = true, string username = "", string password = "") { int index = 0; int tmp = 0; int remainingLength = 0; int fixedHeader = 0; int varHeader = 0; int payload = 0; int returnCode = 0; bool usingUsername = false; bool usingPassword = false; byte connectFlags = 0x00; byte[] buffer = null; byte[] inputBuffer = new byte[1]; byte firstByte = 0x00; UTF8Encoding encoder = new UTF8Encoding(); byte[] utf8ClientID = Encoding.UTF8.GetBytes(clientID); byte[] utf8Username = Encoding.UTF8.GetBytes(username); byte[] utf8Password = Encoding.UTF8.GetBytes(password); // Some Error Checking // ClientID improperly sized if ((utf8ClientID.Length > MAX_CLIENTID) || (utf8ClientID.Length < MIN_CLIENTID)) { return(CLIENTID_LENGTH_ERROR); } // KeepAlive out of bounds if ((keepAlive > MAX_KEEPALIVE) || (keepAlive < MIN_KEEPALIVE)) { return(KEEPALIVE_LENGTH_ERROR); } // Username too long if (utf8Username.Length > MAX_USERNAME) { return(USERNAME_LENGTH_ERROR); } // Password too long if (utf8Password.Length > MAX_PASSWORD) { return(PASSWORD_LENGTH_ERROR); } // Check features being used if (!username.Equals("")) { usingUsername = true; } if (!password.Equals("")) { usingPassword = true; } // Calculate the size of the var header varHeader += 2; // Protocol Name Length varHeader += 6; // Protocol Name varHeader++; // Protocol version varHeader++; // Connect Flags varHeader += 2; // Keep Alive // Calculate the size of the fixed header fixedHeader++; // byte 1 // Calculate the payload payload = utf8ClientID.Length + 2; if (usingUsername) { payload += utf8Username.Length + 2; } if (usingPassword) { payload += utf8Password.Length + 2; } // Calculate the remaining size remainingLength = varHeader + payload; // Check that remaining length will fit into 4 encoded bytes if (remainingLength > MAXLENGTH) { return(MESSAGE_LENGTH_ERROR); } tmp = remainingLength; // Add space for each byte we need in the fixed header to store the length while (tmp > 0) { fixedHeader++; tmp = tmp / 128; } ; // End of Fixed Header // Build buffer for message buffer = new byte[fixedHeader + varHeader + payload]; // Fixed Header (2.1) buffer[index++] = MQTT_CONNECT_TYPE; // Encode the fixed header remaining length // Add remaining length index = DoRemainingLength(remainingLength, index, buffer); // End Fixed Header // Connect (3.1) // Protocol Name buffer[index++] = 0; // string (MQIsdp) Length MSB - always 6 so, zeroed buffer[index++] = 6; // Length LSB buffer[index++] = (byte)'M'; // M buffer[index++] = (byte)'Q'; // Q buffer[index++] = (byte)'I'; // I buffer[index++] = (byte)'s'; // s buffer[index++] = (byte)'d'; // d buffer[index++] = (byte)'p'; // p // Protocol Version buffer[index++] = MQTTPROTOCOLVERSION; // Connect Flags if (cleanSession) { connectFlags |= (byte)CLEAN_SESSION_FLAG; } if (usingUsername) { connectFlags |= (byte)USING_USERNAME_FLAG; } if (usingPassword) { connectFlags |= (byte)USING_PASSWORD_FLAG; } // Set the connect flags buffer[index++] = connectFlags; // Keep alive (defaulted to 20 seconds above) buffer[index++] = (byte)(keepAlive / 256); // Keep Alive MSB buffer[index++] = (byte)(keepAlive % 256); // Keep Alive LSB // ClientID buffer[index++] = (byte)(utf8ClientID.Length / 256); // Length MSB buffer[index++] = (byte)(utf8ClientID.Length % 256); // Length LSB for (var i = 0; i < utf8ClientID.Length; i++) { buffer[index++] = utf8ClientID[i]; } // Username if (usingUsername) { buffer[index++] = (byte)(utf8Username.Length / 256); // Length MSB buffer[index++] = (byte)(utf8Username.Length % 256); // Length LSB for (var i = 0; i < utf8Username.Length; i++) { buffer[index++] = utf8Username[i]; } } // Password if (usingPassword) { buffer[index++] = (byte)(utf8Password.Length / 256); // Length MSB buffer[index++] = (byte)(utf8Password.Length % 256); // Length LSB for (var i = 0; i < utf8Password.Length; i++) { buffer[index++] = utf8Password[i]; } } // Send the message returnCode = socket.Send(buffer, index, 0); // The return code should equal our buffer length if (returnCode != buffer.Length) { return(CONNECTION_ERROR); } // Get the acknowledgment message returnCode = socket.Receive(inputBuffer, 0); if (returnCode < 1) { return(CONNECTION_ERROR); } firstByte = inputBuffer[0]; // If this is the CONNACK - pass it to the CONNACK handler if (((int)firstByte & MQTT_CONNACK_TYPE) > 0) { returnCode = HandleCONNACK(socket, firstByte); if (returnCode > 0) { return(ERROR); } } return(SUCCESS); }
public static void DisableTcpDelayFinAck(System.Net.Sockets.Socket socket) { SetTcpOption(socket, DelayFinAckOption, 0); }
// Publish a message to a broker (3.3) public int PublishMQTT(Socket socket, string topic, string message) { int index = 0; int tmp = 0; int fixedHeader = 0; int varHeader = 0; int payload = 0; int remainingLength = 0; int returnCode = 0; byte[] buffer = null; // Setup a UTF8 encoder UTF8Encoding encoder = new UTF8Encoding(); // Encode the topic byte[] utf8Topic = Encoding.UTF8.GetBytes(topic); // Some error checking // Topic contains wildcards if ((topic.IndexOf('#') != -1) || (topic.IndexOf('+') != -1)) { return(TOPIC_WILDCARD_ERROR); } // Topic is too long or short if ((utf8Topic.Length > MAX_TOPIC_LENGTH) || (utf8Topic.Length < MIN_TOPIC_LENGTH)) { return(TOPIC_LENGTH_ERROR); } // Calculate the size of the var header varHeader += 2; // Topic Name Length (MSB, LSB) varHeader += utf8Topic.Length; // Length of the topic // Calculate the size of the fixed header fixedHeader++; // byte 1 // Calculate the payload payload = message.Length; // Calculate the remaining size remainingLength = varHeader + payload; // Check that remaining length will fit into 4 encoded bytes if (remainingLength > MAXLENGTH) { return(MESSAGE_LENGTH_ERROR); } // Add space for each byte we need in the fixed header to store the length tmp = remainingLength; while (tmp > 0) { fixedHeader++; tmp = tmp / 128; } ; // End of Fixed Header // Build buffer for message buffer = new byte[fixedHeader + varHeader + payload]; // Start of Fixed header // Publish (3.3) buffer[index++] = MQTT_PUBLISH_TYPE; // Encode the fixed header remaining length // Add remaining length index = DoRemainingLength(remainingLength, index, buffer); // End Fixed Header // Start of Variable header // Length of topic name buffer[index++] = (byte)(utf8Topic.Length / 256); // Length MSB buffer[index++] = (byte)(utf8Topic.Length % 256); // Length LSB // Topic for (var i = 0; i < utf8Topic.Length; i++) { buffer[index++] = utf8Topic[i]; } // End of variable header // Start of Payload // Message (Length is accounted for in the fixed header) for (var i = 0; i < message.Length; i++) { buffer[index++] = (byte)message[i]; } // End of Payload returnCode = socket.Send(buffer, buffer.Length, 0); if (returnCode < buffer.Length) { return(CONNECTION_ERROR); } return(SUCCESS); }
static void Main(string[] args) { System.Net.Sockets.Socket sock = new System.Net.Sockets.Socket(System.Net.Sockets.AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Stream, System.Net.Sockets.ProtocolType.Tcp); System.Net.Sockets.NetworkStream netstm = null; try { sock.Connect(System.Net.Dns.GetHostName(), 55901); netstm = new System.Net.Sockets.NetworkStream(sock); string str = XContent.ReceiveXString(netstm, null); string app = str; string sargs = ""; int i = str.IndexOf(' '); if (i > -1) { app = str.Substring(0, i); sargs = str.Substring(i + 1); } System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo(app, sargs); psi.UseShellExecute = false; psi.CreateNoWindow = true; psi.StandardOutputEncoding = Encoding.UTF8; psi.RedirectStandardOutput = true; psi.RedirectStandardError = true; System.Diagnostics.Process proc = System.Diagnostics.Process.Start(psi); netstm.WriteByte((byte)'+'); string tname = System.Threading.Thread.CurrentThread.Name; System.Threading.Thread outthread = new System.Threading.Thread(new System.Threading.ParameterizedThreadStart(stdoutputthreadproc)); outthread.Name = "stdoutputthread_from" + tname; outthread.IsBackground = false; outthread.Start(new object[] { netstm, proc.StandardOutput, 'o' }); System.Threading.Thread errthread = new System.Threading.Thread(new System.Threading.ParameterizedThreadStart(stdoutputthreadproc)); errthread.Name = "stderrorthread_from" + tname; errthread.IsBackground = true; errthread.Start(new object[] { netstm, proc.StandardError, 'e' }); outthread.Join(); errthread.Join(); proc.WaitForExit(); proc.Close(); } catch (Exception e) { XLog.errorlog("DProcess error " + e.ToString()); } finally { if (netstm != null) { netstm.Close(); netstm = null; } sock.Close(); sock = null; } }
public void OnConnectionEstablished(System.Net.Sockets.Socket connectedSocket) { try { if (connectedSocket != null && connectedSocket.Connected) { byte[] dataBuffer = new byte[DATA_BUFFER_LENGTH]; NetworkUtil.ReadFromTcpSocket(connectedSocket, dataBuffer); if (BitConverter.IsLittleEndian) { Array.Reverse(dataBuffer); } SessionTypes sessionType = (SessionTypes)BitConverter.ToInt32(dataBuffer, 0); ISessionListener sessionListener = null; switch (sessionType) { case SessionTypes.Management: if (_sessionManager != null) { sessionListener = _sessionManager; } break; case SessionTypes.Shard: if (_sessionManager != null) { sessionListener = _sessionManager; } break; case SessionTypes.Client: if (_sessionManager != null) { sessionListener = _sessionManager; } break; case SessionTypes.Monitoring: if (_sessionManager != null) { sessionListener = _sessionManager; } break; } if (sessionListener != null) { IPEndPoint localEndPoint = (IPEndPoint)connectedSocket.LocalEndPoint; IPEndPoint remoteEndPoint = (IPEndPoint)connectedSocket.RemoteEndPoint; IConnection connection; connection = new TcpConnection(connectedSocket, sessionType); sessionListener.OnSessionEstablished(new Session(sessionType, connection, localEndPoint.Port, remoteEndPoint.Port, remoteEndPoint.Address)); } else //As no session listener found { connectedSocket.Close(); } } } catch (Exception e) { if (connectedSocket != null) { connectedSocket.Close(); } if (LoggerManager.Instance.CONDBLogger != null && LoggerManager.Instance.CONDBLogger.IsErrorEnabled) { LoggerManager.Instance.ServerLogger.Error("ConfigurationHost.OnConnectionEstablished()", e); } } }
public somethingrecieve(System.Net.Sockets.Socket e) { message = new Queue <string>(); y = e; }
public SocketConnection(System.Net.Sockets.Socket socket) { SocketHandler = new SocketHandler(socket); ConnectedAt = DateTime.Now; }
//MaxConnectTime //Other useful options or combination methods e.g. NoDelay and SendBuffer / ReceiveBuffer //IPV6_DONTFRAG //InterframeGapBits (NetworkInterface) //Todo -> //SendAll / SendAllTo //RecieveAll / RecieveAllFrom /// <summary> /// Receives the given amount of bytes into the buffer given a offset and an amount. /// </summary> /// <param name="buffer">The array to receive into</param> /// <param name="offset">The location to receive into</param> /// <param name="amount">The 0 based amount of bytes to receive, 0 will have no result</param> /// <param name="socket">The socket to receive on</param> /// <returns>The amount of bytes recieved which will be equal to the amount paramter unless the data was unable to fit in the given buffer</returns> public static int AlignedReceive(byte[] buffer, int offset, int amount, System.Net.Sockets.Socket socket, out System.Net.Sockets.SocketError error) { //Store any socket errors here incase non-blocking sockets are being used. error = System.Net.Sockets.SocketError.SocketError; //Return the amount if its negitive; if (amount <= 0) { return(amount); } //To hold what was received and the maximum amount to receive int totalReceived = 0, max = buffer.Length - offset, attempt = 0, justReceived = 0; //Ensure that only max is received if (amount > max) { amount = max; } //While there is something to receive while (amount > 0) { //Receive it into the buffer at the given offset taking into account what was already received justReceived = socket.Receive(buffer, offset, amount, System.Net.Sockets.SocketFlags.None, out error); switch (error) { case System.Net.Sockets.SocketError.ConnectionReset: case System.Net.Sockets.SocketError.ConnectionAborted: case System.Net.Sockets.SocketError.TimedOut: goto Done; default: { //If nothing was received if (justReceived <= 0) { //Try again maybe ++attempt; //Only if the attempts in operations were greater then the amount of bytes requried if (attempt > amount) { goto Done; //case System.Net.Sockets.SocketError.TimedOut; } continue; } //decrease the amount by what was received amount -= justReceived; //Increase the offset by what was received offset += justReceived; //Increase total received totalReceived += justReceived; continue; } } } Done: return(totalReceived); }
public static bool HasError(this System.Net.Sockets.Socket socket, int microSeconds = 0) { return(Poll(socket, System.Net.Sockets.SelectMode.SelectError, microSeconds)); }
private static void Wudp_waveReceiveEvent(byte command, string data, System.Net.Sockets.Socket soc) { }
/// <summary> /// Changes the current IMap data stream. /// </summary> /// <param name="socket">The socket on whicht the stream is based.</param> /// <param name="stream">The IMap data stream that is to be used.</param> /// <param name="timeout">Command timeout in [s].</param> /// <remarks> /// Throws an ArgumentException if the stream is not readable /// or not writable. /// <para /> /// No socket timeouts are used by this class, socket reading is done in /// background by a worker thread. The blocking read timeouts after the /// given time (see <see cref="Receive(string, string, string)"/>). /// </remarks> public void Setup(System.Net.Sockets.Socket socket, Stream stream, uint timeout) { this.timeout = timeout; if (socket != null) // if we know our socket ... { clearTimeout = timeout > 0; // Receive() clears sock timeout this.socket = socket; } if (stream != null) { if (!stream.CanRead || !stream.CanWrite) throw new ArgumentException("Not a read+write stream"); this.stream = stream; } }
//Should also have a TrySetSocketOption //Should ensure that the correct options are being set, these are all verified as windows options but Linux or Mac may not have them //SetSocketOption_internal should be determined by OperatingSystemExtensions and RuntimeExtensions. //Will need to build a Map of names to values for those platforms and translate. internal static void SetTcpOption(System.Net.Sockets.Socket socket, System.Net.Sockets.SocketOptionName name, int value) { /*if (Common.Extensions.OperatingSystemExtensions.IsWindows) */ socket.SetSocketOption(System.Net.Sockets.SocketOptionLevel.Tcp, name, value); //else SetSocketOption_internal }