private void button1_Click(object sender, EventArgs e) { System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch(); var ControllerIPAddress = new IPAddress(new byte[] { 192, 168, 0, 2 }); var ControllerPort = 40001; var ControllerEndPoint = new IPEndPoint(ControllerIPAddress, ControllerPort); _client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); var header = "@"; var command = "00C"; var checksum = "E3"; var end = "\r\n"; var data = header + command + checksum + end; byte[] bytes = new byte[1024]; //Start Connect _connectDone.Reset(); watch.Start(); _client.BeginConnect(ControllerIPAddress, ControllerPort, new AsyncCallback(ConnectCallback), _client); //wait 2s _connectDone.WaitOne(2000, false); var text = (_client.Connected) ? "ok" : "ng"; richTextBox1.AppendText(text + "\r\n"); watch.Stop(); richTextBox1.AppendText("Consumer time: " + watch.ElapsedMilliseconds + "\r\n"); }
/// <summary> /// A connection to our server, always listening asynchronously. /// </summary> /// <param name="socket">The Socket for the connection.</param> /// <param name="args">The SocketAsyncEventArgs for asyncronous recieves.</param> /// <param name="dataReceived">A callback invoked when data is recieved.</param> /// <param name="disconnectedCallback">A callback invoked on disconnection.</param> public ServerConnection(Socket socket, SocketAsyncEventArgs args, DataReceivedCallback dataReceived, DisconnectedCallback disconnectedCallback) { logger = new ElibLogging("data"); this.AuthorizationType = Securtiy.AuthorizationType.Anonymous; lock (this) { var remotIP = socket.RemoteEndPoint as IPEndPoint; var localIP = socket.LocalEndPoint as IPEndPoint; State state = new State() { socket = socket, dataReceived = dataReceived, disconnectedCallback = disconnectedCallback, Device = new Device() { RemoteIP = remotIP.Address.ToString(), LocalIP = localIP.Address.ToString() } }; eventArgs = args; eventArgs.Completed += ReceivedCompleted; eventArgs.UserToken = state; ListenForData(eventArgs); } }
public WebServer() { greenThread = new Thread(green.LightControl); greenThread.Start(); amberThread = new Thread(amber.LightControl); amberThread.Start(); redThread = new Thread(red.LightControl); redThread.Start(); //Initialize Socket class socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //Request and bind to an IP from DHCP server socket.Bind(new IPEndPoint(IPAddress.Any, 80)); string address = Microsoft.SPOT.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces()[0].IPAddress; //Debug print our IP address while (address == "192.168.5.100") { address = Microsoft.SPOT.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces()[0].IPAddress; Thread.Sleep(2000); } Debug.Print(address); //Start listen for web requests socket.Listen(10); ListenForRequest(); }
internal void InitConnect(IPEndPoint serverEndPoint, Action<IPEndPoint, Socket> onConnectionEstablished, Action<IPEndPoint, SocketError> onConnectionFailed, ITcpConnection connection, TimeSpan connectionTimeout) { if (serverEndPoint == null) throw new ArgumentNullException("serverEndPoint"); if (onConnectionEstablished == null) throw new ArgumentNullException("onConnectionEstablished"); if (onConnectionFailed == null) throw new ArgumentNullException("onConnectionFailed"); var socketArgs = _connectSocketArgsPool.Get(); var connectingSocket = new Socket(serverEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp); socketArgs.RemoteEndPoint = serverEndPoint; socketArgs.AcceptSocket = connectingSocket; var callbacks = (CallbacksStateToken) socketArgs.UserToken; callbacks.OnConnectionEstablished = onConnectionEstablished; callbacks.OnConnectionFailed = onConnectionFailed; callbacks.PendingConnection = new PendingConnection(connection, DateTime.UtcNow.Add(connectionTimeout)); AddToConnecting(callbacks.PendingConnection); try { var firedAsync = connectingSocket.ConnectAsync(socketArgs); if (!firedAsync) ProcessConnect(socketArgs); } catch (ObjectDisposedException) { HandleBadConnect(socketArgs); } }
public TCPSocket(Socket from, bool socket_listening) { sock = from; listening = socket_listening; if (socket_listening) { IPEndPoint tmp = (IPEndPoint)sock.LocalEndPoint; port = (ushort)tmp.Port; ep = tmp; } else { IPEndPoint tmp = (IPEndPoint)sock.RemoteEndPoint; port = (ushort)tmp.Port; ep = tmp; } if (sock.Blocking == false) { sock.Blocking = true; } sock.ReceiveBufferSize = 1024 * 64; // 64 kb sock.SendBufferSize = 1024 * 64; // 64 kb }
private server_socket( server_socket templ ) : base() { _server_socket= templ._server_socket; client_socket= templ.client_socket; blocking= templ.blocking; }
public MessageParser(Socket serverSocket, Messaging parent) { this.threadSocket = serverSocket; this.parent = parent; Thread messageParserThread = new Thread(RunThread); messageParserThread.Start(); }
protected static int SetSocketOption(Socket socket, SocketOptionLevel level, SocketOptionName name, int value) { if (((int)socket.GetSocketOption(level, name)) == value) return value; socket.SetSocketOption(level, name, value); return (int)socket.GetSocketOption(level, name); }
public override void InputThread() { try { using (Socket mainSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { mainSocket.Bind(new IPEndPoint(IPAddress.Any, this.Port)); mainSocket.Listen(10); logger.Info("TCP listening on port: {0}", this.Port); byte[] buffer = new byte[65536]; while (!InputThreadQuitRequested()) { if (mainSocket.Poll(1000000, SelectMode.SelectRead)) { Socket childSocket = mainSocket.Accept(); TCPConnection conn = new TCPConnection(this, childSocket); logger.Info("{0} accepted.", conn); conn.Start(); } } } } catch (Exception ex) { RaiseError(ex); } finally { } }
//Connect to the client public void connect() { if (!clientConnected) { IPAddress ipAddress = IPAddress.Any; TcpListener listener = new TcpListener(ipAddress, portSend); listener.Start(); Console.WriteLine("Server is running"); Console.WriteLine("Listening on port " + portSend); Console.WriteLine("Waiting for connections..."); while (!clientConnected) { s = listener.AcceptSocket(); s.SendBufferSize = 256000; Console.WriteLine("Connection accepted from " + s.RemoteEndPoint); byte[] b = new byte[65535]; int k = s.Receive(b); ASCIIEncoding enc = new ASCIIEncoding(); Console.WriteLine("Received:" + enc.GetString(b, 0, k) + ".."); //Ensure the client is who we want if (enc.GetString(b, 0, k) == "hello" || enc.GetString(b, 0, k) == "hellorcomplete") { clientConnected = true; Console.WriteLine(enc.GetString(b, 0, k)); } } } }
public void ConnectIPAddressAny () { IPEndPoint ep = new IPEndPoint (IPAddress.Any, 0); /* UDP sockets use Any to disconnect try { using (Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)) { s.Connect (ep); s.Close (); } Assert.Fail ("#1"); } catch (SocketException ex) { Assert.AreEqual (10049, ex.ErrorCode, "#2"); } */ try { using (Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { s.Connect (ep); s.Close (); } Assert.Fail ("#3"); } catch (SocketException ex) { Assert.AreEqual (10049, ex.ErrorCode, "#4"); } }
public static void Main() { using (Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { // Addressing IPAddress ipAddress = IPAddress.Parse(dottedServerIPAddress); IPEndPoint serverEndPoint = new IPEndPoint(ipAddress, port); // Connecting Debug.Print("Connecting to server " + serverEndPoint + "."); clientSocket.Connect(serverEndPoint); Debug.Print("Connected to server."); using (SslStream sslStream = new SslStream(clientSocket)) { X509Certificate rootCA = new X509Certificate(Resources.GetBytes(Resources.BinaryResources.MyRootCA)); X509Certificate clientCert = new X509Certificate(Resources.GetBytes(Resources.BinaryResources.MyRootCA)); sslStream.AuthenticateAsClient("MyServerName", // Hostname needs to match CN of server cert clientCert, // Authenticate client new X509Certificate[] { rootCA }, // CA certs for verification SslVerification.CertificateRequired, // Verify server SslProtocols.Default // Protocols that may be required ); // Sending byte[] messageBytes = Encoding.UTF8.GetBytes("Hello World!"); sslStream.Write(messageBytes, 0, messageBytes.Length); } }// the socket will be closed here }
static void Main(string[] args) { byte[] receiveBytes = new byte[1024]; int port =8080;//服务器端口 string host = "10.3.0.1"; //服务器ip IPAddress ip = IPAddress.Parse(host); IPEndPoint ipe = new IPEndPoint(ip, port);//把ip和端口转化为IPEndPoint实例 Console.WriteLine("Starting Creating Socket Object"); Socket sender = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//创建一个Socket sender.Connect(ipe);//连接到服务器 string sendingMessage = "Hello World!"; byte[] forwardingMessage = Encoding.ASCII.GetBytes(sendingMessage + "[FINAL]"); sender.Send(forwardingMessage); int totalBytesReceived = sender.Receive(receiveBytes); Console.WriteLine("Message provided from server: {0}", Encoding.ASCII.GetString(receiveBytes,0,totalBytesReceived)); //byte[] bs = Encoding.ASCII.GetBytes(sendStr); sender.Shutdown(SocketShutdown.Both); sender.Close(); Console.ReadLine(); }
static void Main(string[] args) { var m_Config = new ServerConfig { Port = 911, Ip = "Any", MaxConnectionNumber = 1000, Mode = SocketMode.Tcp, Name = "CustomProtocolServer" }; var m_Server = new CustomProtocolServer(); m_Server.Setup(m_Config, logFactory: new ConsoleLogFactory()); m_Server.Start(); EndPoint serverAddress = new IPEndPoint(IPAddress.Parse("127.0.0.1"), m_Config.Port); using (Socket socket = new Socket(serverAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp)) { socket.Connect(serverAddress); var socketStream = new NetworkStream(socket); var reader = new StreamReader(socketStream, Encoding.ASCII, false); string charSource = Guid.NewGuid().ToString().Replace("-", string.Empty) + Guid.NewGuid().ToString().Replace("-", string.Empty) + Guid.NewGuid().ToString().Replace("-", string.Empty); Random rd = new Random(); var watch = Stopwatch.StartNew(); for (int i = 0; i < 10; i++) { int startPos = rd.Next(0, charSource.Length - 2); int endPos = rd.Next(startPos + 1, charSource.Length - 1); var currentMessage = charSource.Substring(startPos, endPos - startPos + 1); byte[] requestNameData = Encoding.ASCII.GetBytes("ECHO"); socketStream.Write(requestNameData, 0, requestNameData.Length); var data = Encoding.ASCII.GetBytes(currentMessage); socketStream.Write(new byte[] { (byte)(data.Length / 256), (byte)(data.Length % 256) }, 0, 2); socketStream.Write(data, 0, data.Length); socketStream.Flush(); // Console.WriteLine("Sent: " + currentMessage); var line = reader.ReadLine(); //Console.WriteLine("Received: " + line); //Assert.AreEqual(currentMessage, line); } watch.Stop(); Console.WriteLine(watch.ElapsedMilliseconds); } Console.ReadLine(); }
public CruncherClient(string serverAddress, int port) { mybuffer = new byte[MAX_BUFFER_SIZE]; this.connection = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); this.server = Globals.ServerURL; this.port = System.Convert.ToInt32(Globals.ServerPort); }
protected override void RecieveCallback(IAsyncResult Result) { DatagramState Dstate = (DatagramState)Result.AsyncState; int bytes = 0; Socket S = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); S.Bind(new IPEndPoint(IPAddress.Any, 0)); Socket past = Dstate.ClientSocket; Dstate.ClientSocket = S; try { bytes = past.EndReceiveFrom(Result, ref Dstate.EndPoint); } catch (Exception e) { Next.Set(); Send("Respect the buffer size which is " + DatagramState.BufferSize.ToString(), Dstate); return; } if (bytes>0) { string content = ""; Dstate.MsgBuilder.Append(Encoding.ASCII.GetString(Dstate.Buffer, 0, bytes)); content = Dstate.MsgBuilder.ToString(); Next.Set(); try { string r = Calculate(content).ToString(); Send(r, Dstate); } catch (Exception e) { Send(e.Message, Dstate); } } }
/// <summary> /// Constructeur /// </summary> /// <param name="port">Port d'ecoute</param> /// <param name="cl"></param> public Recepteur(int port, Game1 cl) { this._client = cl; this._portReception = port; this._ip = GestionReseau.GetMyLocalIp(); _reception = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); }
public PackRawServerSide(Socket sock) : base(sock) { onMessageReadyToTx = new OnMessageReadyToTx(OnMsgRead4Tx); m_Id = sock.RemoteEndPoint; senderPackLib = new SenderPackLib.SenderPackLib(m_Id, onMessageReadyToTx); }
/// <summary> /// Connects to the node debugger. /// </summary> public void Connect() { Socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); Socket.NoDelay = true; Socket.Connect(new DnsEndPoint(_hostName, _portNumber)); StartListenerThread(); }
private static void Server() { list = new List<IPAddress>(); const ushort data_size = 0x400; // = 1024 byte[] data; while (ServerRun) { Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); IPEndPoint iep = new IPEndPoint(IPAddress.Any, BroadcastRecievePort); try { sock.Bind(iep); EndPoint ep = (EndPoint)iep; data = new byte[data_size]; if (!ServerRun) break; int recv = sock.ReceiveFrom(data, ref ep); string stringData = System.Text.Encoding.ASCII.GetString(data, 0, recv); if (!list.Contains(IPAddress.Parse(ep.ToString().Split(':')[0]))) list.Add(IPAddress.Parse(ep.ToString().Split(':')[0])); data = new byte[data_size]; if (!ServerRun) break; recv = sock.ReceiveFrom(data, ref ep); stringData = System.Text.Encoding.ASCII.GetString(data, 0, recv); if (!list.Contains(IPAddress.Parse(ep.ToString().Split(':')[0]))) list.Add(IPAddress.Parse(ep.ToString().Split(':')[0])); sock.Close(); } catch { } } }
/// <overloads> /// Initializes a new instance of the <see cref="BluetoothListener"/> class. /// </overloads> /// ---- /// <summary> /// Initializes a new instance of the <see cref="BluetoothListener"/> class /// to listen on the specified service identifier. /// </summary> /// <param name="service">The Bluetooth service to listen for.</param> /// <remarks> /// <para> /// An SDP record is published on successful <see cref="M:InTheHand.Net.Sockets.BluetoothListener.Start"/> /// to advertise the server. /// A generic record is created, containing the essential <c>ServiceClassIdList</c> /// and <c>ProtocolDescriptorList</c> attributes. The specified service identifier is /// inserted into the former, and the RFCOMM Channel number that the server is /// listening on is inserted into the latter. See the Bluetooth SDP specification /// for details on the use and format of SDP records. /// </para><para> /// If a SDP record with more elements is required, then use /// one of the other constructors that takes an SDP record e.g. /// <see cref="M:InTheHand.Net.Sockets.BluetoothListener.#ctor(System.Guid,InTheHand.Net.Bluetooth.ServiceRecord)"/>, /// or when passing it as a byte array /// <see cref="M:InTheHand.Net.Sockets.BluetoothListener.#ctor(System.Guid,System.Byte[],System.Int32)"/>. /// The format of the generic record used here is shown there also. /// </para><para> /// Call the <see cref="M:InTheHand.Net.Sockets.BluetoothListener.Start"/> /// method to begin listening for incoming connection attempts. /// </para> /// </remarks> public BluetoothListener(Guid service) { InitServiceRecord(service); this.serverEP = new BluetoothEndPoint(BluetoothAddress.None, service); serverSocket = new Socket(AddressFamily32.Bluetooth, SocketType.Stream, BluetoothProtocolType.RFComm); m_optionHelper = new BluetoothClient.SocketOptionHelper(serverSocket); }
protected override bool RecordOpenedSocket(Socket sock) { ThreadTrackingStatistic.FirstClientConnectedStartTracking(); GrainId client; if (!ReceiveSocketPreample(sock, true, out client)) return false; // refuse clients that are connecting to the wrong cluster if (client.Category == UniqueKey.Category.GeoClient) { if(client.Key.ClusterId != Silo.CurrentSilo.ClusterId) { Log.Error(ErrorCode.GatewayAcceptor_WrongClusterId, string.Format( "Refusing connection by client {0} because of cluster id mismatch: client={1} silo={2}", client, client.Key.ClusterId, Silo.CurrentSilo.ClusterId)); return false; } } else { //convert handshake cliendId to a GeoClient ID if (!string.IsNullOrEmpty(Silo.CurrentSilo.ClusterId)) { client = GrainId.NewClientId(client.PrimaryKey, Silo.CurrentSilo.ClusterId); } } gateway.RecordOpenedSocket(sock, client); return true; }
public server_socket( Object name, int port ) : base() { try { /* _server_socket = new Socket( AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp ); */ /* _server_socket.Bind( new IPEndPoint( 0, port ) ); */ IPEndPoint endpoint; if( name != bigloo.foreign.BFALSE ) { String server = bigloo.foreign.newstring( name ); IPHostEntry host = Dns.Resolve(server); IPAddress address = host.AddressList[0]; endpoint = new IPEndPoint(address, port); } else { endpoint = new IPEndPoint( 0, port ); } _server_socket = new Socket( endpoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp ); _server_socket.Bind( endpoint ); _server_socket.Listen( 10 ); } catch (Exception e) { socket_error( "make-server-socket", "cannot create socket (" + e.Message + ")", new bint( port ) ); } }
public TCPSocket(ushort socket_port, bool mode_blocking) { port = socket_port; sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); sock.Blocking = mode_blocking; }
public FTPClient(string Server, int Port = 21, string Username = "******", string Password = @"*****@*****.**") { PasvMode = true; #if DEBUG Console.WriteLine(@"FTP: Connecting to {0}...",Server); #endif IPAddress addr; try { CommandSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); addr = Dns.GetHostEntry(Server).AddressList[0]; CommandSocket.Connect(addr,Port); } catch (Exception ex) { if (CommandSocket != null && CommandSocket.Connected) CommandSocket.Close(); throw new FtpException("Couldn't connect to remote server", ex); } #if DEBUG Console.WriteLine(@"FTP: TCP connection estabilished " + Server); #endif ReadResponse(); if (ResponseCode != 220) { //close throw new FtpException(Response.Substring(4),ResponseCode,"connnect"); } #if DEBUG Console.WriteLine(@"FTP: Authorizing as {0}, {1}", Username, Password); #endif SendCommand("USER " + Username); if (!(ResponseCode == 331 || ResponseCode == 230 || ResponseCode == 220)) { //close throw new FtpException(Response.Substring(4),ResponseCode,"USER"); } if (ResponseCode != 230) { SendCommand("PASS " + Password); if (!(ResponseCode == 230 || ResponseCode == 202)) { //close throw new FtpException(Response.Substring(4),ResponseCode,"PASS"); } } #if DEBUG Console.WriteLine(@"FTP: FTP connection estabilished " + Server); #endif }
private void StartListening() { context = new Context(1); socket = context.Socket(SocketType.PULL); socket.Connect("tcp://127.0.0.1:8400"); // Connect to 8400 UpdateTextBox("Connected to 127.0.0.1:8400"); }
private void InitializeNetwork() { lock (m_initializeLock) { m_configuration.Lock(); if (m_status == NetPeerStatus.Running) return; InitializePools(); m_releasedIncomingMessages.Clear(); m_unsentUnconnectedMessages.Clear(); m_handshakes.Clear(); // bind to socket IPEndPoint iep = null; iep = new IPEndPoint(m_configuration.LocalAddress, m_configuration.Port); EndPoint ep = (EndPoint)iep; m_socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); m_socket.ReceiveBufferSize = m_configuration.ReceiveBufferSize; m_socket.SendBufferSize = m_configuration.SendBufferSize; m_socket.Blocking = false; m_socket.Bind(ep); IPEndPoint boundEp = m_socket.LocalEndPoint as IPEndPoint; LogDebug("Socket bound to " + boundEp + ": " + m_socket.IsBound); m_listenPort = boundEp.Port; m_receiveBuffer = new byte[m_configuration.ReceiveBufferSize]; m_sendBuffer = new byte[m_configuration.SendBufferSize]; m_readHelperMessage = new NetIncomingMessage(NetIncomingMessageType.Error); m_readHelperMessage.m_data = m_receiveBuffer; byte[] macBytes = new byte[8]; NetRandom.Instance.NextBytes(macBytes); #if IS_MAC_AVAILABLE System.Net.NetworkInformation.PhysicalAddress pa = NetUtility.GetMacAddress(); if (pa != null) { macBytes = pa.GetAddressBytes(); LogVerbose("Mac address is " + NetUtility.ToHexString(macBytes)); } else { LogWarning("Failed to get Mac address"); } #endif byte[] epBytes = BitConverter.GetBytes(boundEp.GetHashCode()); byte[] combined = new byte[epBytes.Length + macBytes.Length]; Array.Copy(epBytes, 0, combined, 0, epBytes.Length); Array.Copy(macBytes, 0, combined, epBytes.Length, macBytes.Length); m_uniqueIdentifier = BitConverter.ToInt64(SHA1.Create().ComputeHash(combined), 0); m_status = NetPeerStatus.Running; } }
/// <summary> /// Constructor for a local proxy's request handler. /// </summary> /// <param name="proxy">Proxy this request handler belongs to.</param> /// <param name="socket">Client socket.</param> public LocalRequestHandler(RCLocalProxy proxy, Socket socket) : base(proxy, socket) { _requestId = _proxy.NextRequestId; _proxy.NextRequestId = _proxy.NextRequestId + 1; _requestTimeout = LOCAL_REQUEST_PACKAGE_DEFAULT_TIMEOUT; }
static string PostStream (Mono.Security.Protocol.Tls.SecurityProtocolType protocol, string url, byte[] buffer) { Uri uri = new Uri (url); string post = "POST " + uri.AbsolutePath + " HTTP/1.0\r\n"; post += "Content-Type: application/x-www-form-urlencoded\r\n"; post += "Content-Length: " + (buffer.Length + 5).ToString () + "\r\n"; post += "Host: " + uri.Host + "\r\n\r\n"; post += "TEST="; byte[] bytes = Encoding.Default.GetBytes (post); IPHostEntry host = Dns.Resolve (uri.Host); IPAddress ip = host.AddressList [0]; Socket socket = new Socket (ip.AddressFamily, SocketType.Stream, ProtocolType.Tcp); socket.Connect (new IPEndPoint (ip, uri.Port)); NetworkStream ns = new NetworkStream (socket, false); SslClientStream ssl = new SslClientStream (ns, uri.Host, false, protocol); ssl.ServerCertValidationDelegate += new CertificateValidationCallback (CertificateValidation); ssl.Write (bytes, 0, bytes.Length); ssl.Write (buffer, 0, buffer.Length); ssl.Flush (); StreamReader reader = new StreamReader (ssl, Encoding.UTF8); string result = reader.ReadToEnd (); int start = result.IndexOf ("\r\n\r\n") + 4; start = result.IndexOf ("\r\n\r\n") + 4; return result.Substring (start); }
private static bool Discover() { Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); s.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1); byte[] data = Encoding.ASCII.GetBytes(req); IPEndPoint ipe = new IPEndPoint(IPAddress.Broadcast, 1900); byte[] buffer = new byte[0x1000]; DateTime start = DateTime.Now; try { do { s.SendTo(data, ipe); s.SendTo(data, ipe); s.SendTo(data, ipe); int length = 0; do { length = s.Receive(buffer); string resp = Encoding.ASCII.GetString(buffer, 0, length); if (resp.Contains("upnp:rootdevice")) { resp = resp.Substring(resp.ToLower().IndexOf("location:") + 9); resp = resp.Substring(0, resp.IndexOf("\r")).Trim(); if (!string.IsNullOrEmpty(_serviceUrl = GetServiceUrl(resp))) { _descUrl = resp; return true; } } } while (length > 0); } while (start.Subtract(DateTime.Now) < _timeout); return false; } catch { return false; } }
public void Send(byte[] buffer, bool sync) { Socket.Send(buffer, sync ? SendFlags.Synchronous : SendFlags.None); }
/// <summary> /// Executes the BnFTP request, downloading the file to where <see cref="BnFtpRequestBase.LocalFileName">LocalFileName</see> /// specifies, and closes the connection. /// </summary> /// <remarks> /// <para>By default, <c>LocalFileName</c> is the same name as the remote file, which will cause the file /// to be saved in the local application path. The desired location of the file must be set before /// <b>ExecuteRequest</b> is called.</para> /// </remarks> /// <exception cref="IOException">Thrown if the local file cannot be written.</exception> /// <exception cref="SocketException">Thrown if the remote host closes the connection prematurely.</exception> public override void ExecuteRequest() { DataBuffer buffer = new DataBuffer(); buffer.InsertInt16((short)(33 + FileName.Length)); buffer.InsertInt16(0x0100); buffer.InsertDwordString("IX86"); buffer.InsertDwordString(Product); if (m_ad) { buffer.InsertInt32(m_adId); buffer.InsertDwordString(m_adExt); } else { buffer.InsertInt64(0); } // currently resuming is not supported buffer.InsertInt32(0); if (FileTime.HasValue) { buffer.InsertInt64(FileTime.Value.ToFileTimeUtc()); } else { buffer.InsertInt64(0); } buffer.InsertCString(FileName); Socket sck = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); sck.Connect(Server, 6112); sck.Send(new byte[] { 2 }); sck.Send(buffer.GetData(), 0, buffer.Count, SocketFlags.None); byte[] hdrLengthBytes = new byte[2]; sck.Receive(hdrLengthBytes, 2, SocketFlags.None); int hdrLen = BitConverter.ToInt16(hdrLengthBytes, 0); Trace.WriteLine(hdrLen, "Header Length"); byte[] hdrBytes = new byte[hdrLen - 2]; sck.Receive(hdrBytes, hdrLen - 2, SocketFlags.None); DataReader rdr = new DataReader(hdrBytes); rdr.Seek(2); int fileSize = rdr.ReadInt32(); this.FileSize = fileSize; rdr.Seek(8); long fileTime = rdr.ReadInt64(); string name = rdr.ReadCString(); if (string.Compare(name, FileName, StringComparison.OrdinalIgnoreCase) != 0 || FileSize == 0) { throw new FileNotFoundException(Resources.bnftp_filenotfound); } Trace.WriteLine(fileSize, "File Size"); byte[] data = ReceiveLoop(sck, fileSize); sck.Close(); FileStream fs = new FileStream(LocalFileName, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None); fs.SetLength(fileSize); fs.Write(data, 0, fileSize); fs.Flush(); fs.Close(); DateTime time = DateTime.FromFileTimeUtc(fileTime); File.SetLastWriteTimeUtc(LocalFileName, time); }
public static void Main() { int recv; byte[] data = new byte[1024]; //Сетевая конечная точка в виде адреса и номера порта IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 9050); // Создание нового сокета (схема адресации, тип сокета, протокол) Socket SrvSock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); //Связываем новый сокет с локальной конечной точкой SrvSock.Bind(ipep); Console.WriteLine("Ожидаем соединения с клиентом..."); //создаем конечную точку по адресу сокета. Т.е. будем "слушать" порты //и контролировать все сетевые интерфейсы IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0); //Получаем конечную удаленную точку EndPoint Remote = (EndPoint)(sender); //Получаем сообщение от клиента (типа, "Клиент успешно подключился!") recv = SrvSock.ReceiveFrom(data, ref Remote); //Отображаем сообщение о успешно подключенном клиенте Console.Write("Сообщение получено от {0}:", Remote.ToString()); Console.WriteLine(Encoding.UTF8.GetString(data, 0, recv)); //Отправляем клиенту сообщение об успешном подключении string welcome = "Подключение к серверу успешно!"; data = Encoding.UTF8.GetBytes(welcome); SrvSock.SendTo(data, data.Length, SocketFlags.None, Remote); //Бесконечный цикл. while (true) { //Объявляем новый массив под пришедшие данные. data = new byte[1024]; //Получение данных... recv = SrvSock.ReceiveFrom(data, ref Remote); //Перевод принятых байтов в строку string str = Encoding.UTF8.GetString(data, 0, recv); //Если пришла команда выхода //Завершаем работу сокета и программы if (str == "exit") { break; } Console.WriteLine("Получили данные: " + str); //Записываем в переменную size новый размер файла (после процедуры prntofile) double size = prntofile(str); //Отображаем форматированное сообщение string input = "Строка успешно записана!\nНовый размер файла: " + size + " байт."; Console.WriteLine(">" + input + "\n"); //Перевод отсылаемой строки в байты data = Encoding.UTF8.GetBytes(input); //Отсылаем серверу строку (переведенную в байты) SrvSock.SendTo(data, data.Length, SocketFlags.None, Remote); } }
public SocketClientHelper(string name, Socket sk, IPEndPoint ipe) { userName = name; socket = sk; endPoint = ipe; }
private void bw_DoWork(object sender, DoWorkEventArgs e) { try { socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); IPEndPoint RHost = new IPEndPoint(Dns.GetHostEntry(URI.Host).AddressList[0], URI.Port); if (iTimeout != -1) { socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, iTimeout); socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, iTimeout); BackgroundWorker bwTimeout = new BackgroundWorker(); bwTimeout.DoWork += new DoWorkEventHandler(bwTimeout_DoWork); bwTimeout.RunWorkerAsync(); } State = ReqState.Connecting; socket.Connect(RHost); State = ReqState.Requesting; if (ConMode == "POST") { outHeaders.Add("Content-Type: application/x-www-form-urlencoded"); } string ReqStr = ConMode + " " + URI.PathAndQuery + " HTTP/1.0\r\n" + outHeaders; if (ConMode == "POST") { ReqStr += Postdata; } SentPacket = ReqStr + "\r\n\r\n>"; byte[] bPck = System.Text.Encoding.ASCII.GetBytes(ReqStr); foreach (byte btPck in bPck) { SentPacket += btPck + " "; } socket.Send(System.Text.Encoding.ASCII.GetBytes(ReqStr)); if (ParseHeader()) { string tFName = ""; do { tFName = tmpPath + "wanr_" + RandomChars(20) + ".tmp"; }while (File.Exists(tFName)); FileStream streamOut = File.Open(tFName, FileMode.Create, FileAccess.Write, FileShare.ReadWrite); BinaryWriter writer = new BinaryWriter(streamOut); byte[] RecvBuffer = new byte[cSize]; int nBytes, nTotalBytes = 0; while ((nBytes = socket.Receive(RecvBuffer, 0, cSize, SocketFlags.None)) > 0) { nTotalBytes += nBytes; State = ReqState.Downloading; Progress = Math.Round(((double)100 - ((double)cLength - (double)nTotalBytes) * (double)100 / (double)cLength), 1); writer.Write(RecvBuffer, 0, nBytes); if (ReturnStr) { Response += Encoding.ASCII.GetString(RecvBuffer, 0, nBytes); } } writer.Close(); streamOut.Close(); streamOut.Dispose(); socket.Close(); long tStart = Tick(); if (!File.Exists(tFName)) { wrErrlog("Poll1 false"); } while (!File.Exists(tFName)) { System.Threading.Thread.Sleep(10); if (Tick() > tStart + 2000) { break; } } if (!File.Exists(tFName)) { wrErrlog("Poll2 false"); } if (File.Exists(tFName)) { if (ReturnStr) { System.IO.StreamReader strmIn = new System.IO.StreamReader(tFName, Encoding.GetEncoding("iso-8859-1")); Response = strmIn.ReadToEnd(); strmIn.Close(); strmIn.Dispose(); } if (Filename != "") { File.Delete(Filename); File.Move(tFName, Filename); } else { File.Delete(tFName); } } } } catch (Exception ex) { wrExThrow(ex.Message, ex.StackTrace); } State = ReqState.Completed; Progress = 100; isReady = true; }
/// <summary> /// Constructs a new <code>OncRpcTcpClient</code> object, which connects /// to the ONC/RPC server at <code>host</code> for calling remote procedures /// of the given { program, version }. /// </summary> /// <remarks> /// Constructs a new <code>OncRpcTcpClient</code> object, which connects /// to the ONC/RPC server at <code>host</code> for calling remote procedures /// of the given { program, version }. /// <p>Note that the construction of an <code>OncRpcTcpClient</code> /// object will result in communication with the portmap process at /// <code>host</code> if <code>port</code> is <code>0</code>. /// </remarks> /// <param name="host">The host where the ONC/RPC server resides.</param> /// <param name="program">Program number of the ONC/RPC server to call.</param> /// <param name="version">Program version number.</param> /// <param name="port"> /// The port number where the ONC/RPC server can be contacted. /// If <code>0</code>, then the <code>OncRpcUdpClient</code> object will /// ask the portmapper at <code>host</code> for the port number. /// </param> /// <param name="bufferSize"> /// Size of receive and send buffers. In contrast to /// UDP-based ONC/RPC clients, messages larger than the specified /// buffer size can still be sent and received. The buffer is only /// necessary to handle the messages and the underlaying streams will /// break up long messages automatically into suitable pieces. /// Specifying zero will select the default buffer size (currently /// 8192 bytes). /// </param> /// <param name="timeout"> /// Maximum timeout in milliseconds when connecting to /// the ONC/RPC server. If negative, a default implementation-specific /// timeout setting will apply. <i>Note that this timeout only applies /// to the connection phase, but <b>not</b> to later communication.</i> /// </param> /// <exception cref="OncRpcException">if an ONC/RPC error occurs.</exception> /// <exception cref="System.IO.IOException">if an I/O error occurs.</exception> /// <exception cref="org.acplt.oncrpc.OncRpcException"></exception> public OncRpcTcpClient(IPAddress host, int program, int version, int port , int bufferSize, int timeout, bool useSecurePort) : base(host, program, version, port, org.acplt.oncrpc.OncRpcProtocols .ONCRPC_TCP) { // // Construct the inherited part of our object. This will also try to // lookup the port of the desired ONC/RPC server, if no port number // was specified (port = 0). // // // Let the host operating system choose which port (and network // interface) to use. Then set the buffer sizes for sending and // receiving UDP datagrams. Finally set the destination of packets. // if (bufferSize == 0) { bufferSize = 128000; } // default setting if (bufferSize < 1024) { bufferSize = 1024; } // // Note that we use this.port at this time, because the superclass // might have resolved the port number in case the caller specified // simply 0 as the port number. // // Construct the socket and connect socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); if (useSecurePort) { var localEp = new IPEndPoint(IPAddress.Any, GetLocalPort()); socket.Bind(localEp); } IPEndPoint endPoint = new IPEndPoint(host, this.port); socket.Connect(endPoint); if (timeout >= 0) { socket.SendTimeout = timeout; socket.ReceiveTimeout = timeout; } socket.NoDelay = true; if (socket.SendBufferSize < bufferSize) { socket.SendBufferSize = bufferSize; } if (socket.ReceiveBufferSize < bufferSize) { socket.ReceiveBufferSize = bufferSize; } // // Create the necessary encoding and decoding streams, so we can // communicate at all. // sendingXdr = new org.acplt.oncrpc.XdrTcpEncodingStream(socket, bufferSize); receivingXdr = new org.acplt.oncrpc.XdrTcpDecodingStream(socket, bufferSize); }
//接收消息 void ReceiveCustomer(Socket client, object _) { _logger.LogDebug("新的HTTP请求"); try { //定义byte数组存放从客户端接收过来的数据 byte[] buffer = new byte[1024]; int count; try { count = client.Receive(buffer); if (count == 0) { client.Close(); return; } } catch (SocketException ex) { _logger.LogError(ex.Message); if (client.Connected) { client.Close(); } return; } catch (Exception ex) { _logger.LogError(ex); throw; } //将字节转换成字符串 string words = Encoding.UTF8.GetString(buffer, 0, count); // 正则获取Host String Host = string.Empty; var pattern = @"Host:.+"; var collection = Regex.Matches(words, pattern); if (collection.Count == 0) { _logger.LogError($"Host异常:{words}"); return; } else { Host = collection[0].Value; } var domain = Host.Split(":")[1].Trim(); _logger.LogDebug($"Host: {domain}"); WebInfo web; if (!WebList.TryGetValue(domain, out web)) { _logger.LogError($"客户端不存在:'{domain}'"); _logger.LogDebug(words); return; } if (!web.Socket.Connected) { _logger.LogError($"客户端已下线:'{domain}'"); WebList.Remove(domain); return; } var msgid = Guid.NewGuid().ToString(); byte[] bytes = new byte[count]; Array.Copy(buffer, bytes, count); newRequest.Add(msgid, new NewRequest { CustomerClient = client, Buffer = bytes }); web.Socket.Send(new Message <NewCustomerMassage> { MessageType = MessageType.S_NewCustomer, Content = new NewCustomerMassage { MsgId = msgid, WebConfig = web.WebConfig } }); } catch (Exception ex) { _logger.LogError(ex); } }
//初始化监听 public ServerStart(int max) { server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //设定服务器最大连接人数 maxClient = max; }
public void PairToDevice(string name, bool known) { Task.Run(async() => { if (BtAdapter.IsEnabled) { if (BtAdapter.IsDiscovering) { BtAdapter.CancelDiscovery(); } ReceivingConnection = false; FileManager file = new FileManager(); file.SaveDevice(name); BluetoothDevice Device = null; if (known) { foreach (BluetoothDevice device in PairedDevices) { if (device.Name == name) { Device = device; } } } else { foreach (BluetoothDevice device in BGData.bluetoothDevices) { if (device.Name == name) { Device = device; } } } UUID uuid = UUID.FromString("00001101-0000-1000-8000-00805f9b34fb"); if ((int)Android.OS.Build.VERSION.SdkInt >= 10) // Gingerbread 2.3.3 2.3.4 { Socket = Device.CreateInsecureRfcommSocketToServiceRecord(uuid); } else { Socket = Device.CreateRfcommSocketToServiceRecord(uuid); } if (Socket != null) { try { await Socket.ConnectAsync(); Master = true; Xamarin.Forms.Device.BeginInvokeOnMainThread(() => { ToastLoader toastLoader = new ToastLoader(); toastLoader.Show("Connected To Player"); BGStuff.mainPage.IsLoading = false; SetupChat(); MainPage.StatSetupGame(); }); } catch (Exception ex) { Xamarin.Forms.Device.BeginInvokeOnMainThread(() => { ToastLoader toastLoader = new ToastLoader(); toastLoader.Show(ex.Message); BGStuff.mainPage.IsLoading = false; ReceivingConnection = true; ReceivePair(); }); } } } }); }
public void PairToDevice() { Task.Run(async() => { if (BtAdapter.IsEnabled) { if (BtAdapter.IsDiscovering) { BtAdapter.CancelDiscovery(); } List <BluetoothDevice> devices = BtAdapter.BondedDevices.ToList(); BluetoothDevice tempDevice = null; string tempstring = ""; FileManager file = new FileManager(); tempstring = file.GetDevice(); await Task.Delay(300); Device.BeginInvokeOnMainThread(() => { ToastLoader toast = new ToastLoader(); toast.Show(tempstring); }); await Task.Delay(500); for (int i = 0; i < devices.Count; i++) { if (tempstring == devices[i].Name) { tempDevice = devices[i]; } } ReceivingConnection = false; UUID uuid = UUID.FromString("00001101-0000-1000-8000-00805f9b34fb"); BluetoothSocket temp = null; try { if ((int)Android.OS.Build.VERSION.SdkInt >= 10) // Gingerbread 2.3.3 2.3.4 { temp = tempDevice.CreateInsecureRfcommSocketToServiceRecord(uuid); } else { temp = tempDevice.CreateRfcommSocketToServiceRecord(uuid); } Socket = temp; } catch (Exception ex) { Device.BeginInvokeOnMainThread(() => { ToastLoader toastLoader = new ToastLoader(); toastLoader.Show(ex.Message); }); } if (Socket != null) { try { await Socket.ConnectAsync(); Master = true; Device.BeginInvokeOnMainThread(() => { ToastLoader toastLoader = new ToastLoader(); toastLoader.Show("Reconnected To Player"); }); SetupChat(); if (BGStuff.Reconnecting) { Device.BeginInvokeOnMainThread(() => { BGStuff.reconnectionPage.Navigation.PopAsync(); }); await Task.Delay(500); BGStuff.Reconnecting = false; Pairing = false; BGStuff.reconnectionPage = null; ReadMessage(); } else { MainPage.StatSetupGame(); } } catch (Exception ex) { if (!BGStuff.Reconnecting) { Device.BeginInvokeOnMainThread(() => { ToastLoader toastLoader = new ToastLoader(); toastLoader.Show(ex.Message); }); ReceivingConnection = true; ReceivePair(); } else { Device.BeginInvokeOnMainThread(() => { ToastLoader toastLoader = new ToastLoader(); toastLoader.Show(ex.Message); }); } } } } }); }
public HydraConnection(Socket socket) { Socket = socket; }
public void Handle() { NetworkStream networkStream = null; try { bool loop = true; IPEndPoint ipep = (IPEndPoint)Socket.RemoteEndPoint; IPAddress = ipep.Address; networkStream = new NetworkStream(Socket); try { Session = new SecureSession(networkStream, Certificates.SecurityParameters); Session.PerformServerHandshake(Certificates.Certificate); } catch { loop = false; } while (loop) { HydraRequest request = null; try { request = new HydraRequest(this); } catch { break; } Modules.IModule module = null; switch (request.Module) { case "feed": { module = new Modules.FeedModule(this); break; } case "profile": { module = new Modules.ProfileModule(this); break; } case "onesite_proxy": { module = new Modules.OnesiteProxyModule(this); break; } case "ugc": { module = new Modules.UgcModule(this); break; } default: { HydraResponse response = new HydraResponse(this); response.StatusCode = 404; response.Status = "File Not Found"; response.Payload = new byte[0]; response.Send(); break; } } if (module != null) module.HandleRequest(request); } } catch (Exception ex) { } try { Session.Close(); networkStream.Flush(); networkStream.Close(); Socket.Disconnect(false); Socket.Dispose(); } catch { } }
protected virtual void WriteResponseStream(Socket client, Stream response, long length, string filename, long offset) { if (client == null || !client.Connected) { return; } else if (response == null) { throw new ArgumentNullException("response"); } else if (length < 1) { throw new ArgumentOutOfRangeException("length", "Must be > 0"); } else if (offset < 0) { throw new ArgumentOutOfRangeException("offset", "Must be positive."); } using (BinaryWriter writer = new BinaryWriter(new NetworkStream(client, false))) { string headers = "HTTP/1.1 200 OK\r\n"; if (offset > 0) { headers = "HTTP/1.1 206 Partial Content\r\n"; headers += String.Format("Content-Range: {0}-{1}\r\n", offset, offset + length); } if (length > 0) { headers += String.Format("Content-Length: {0}\r\n", length); } if (filename != null) { headers += String.Format("Content-Disposition: attachment; filename=\"{0}\"\r\n", filename.Replace("\"", "\\\"")); } headers += "Connection: close\r\n"; headers += "\r\n"; writer.Write(Encoding.UTF8.GetBytes(headers)); using (BinaryReader reader = new BinaryReader(response)) { while (true) { byte [] buffer = reader.ReadBytes(ChunkLength); if (buffer == null) { break; } writer.Write(buffer); if (buffer.Length < ChunkLength) { break; } } } } }
public OvermindSession(Socket socket) : base(socket) { MessageReceivedEvent += Overmind.Instance.MessageProcessor.MessageReceivedEventHandler; }
public void Send(byte[] buffer) { Socket.Send(buffer, SendFlags.None); }
private protected override unsafe SendError SendTo(Socket arg0, in PacketInfo packetInfo)
public void Start() { IDictionary <string, Func <string[], string> > actionList = new Dictionary <string, Func <string[], string> >(); WordDictionary wordDictionary = new WordDictionary(); IPEndPoint ipPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), port); Socket listenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); Action <object> proc_action = (obj) => { Socket handler = (Socket)obj; StringBuilder builder = new StringBuilder(); int bytes = 0; byte[] data = new byte[256]; do { bytes = handler.Receive(data); builder.Append(Encoding.Unicode.GetString(data, 0, bytes)); }while (handler.Available > 0); string msg = builder.ToString(); Console.WriteLine(DateTime.Now.ToShortTimeString() + ": " + builder.ToString()); //read command Regex rgx = new Regex(@"^(?<cmd>\w+)\s(?<prs>.+)*$"); Match match = rgx.Match(msg); string cmd = match.Groups["cmd"].Value; string prs = match.Groups["prs"].Value; string res = actionList[cmd].Invoke(prs.Split(' ')); // отправляем ответ data = Encoding.Unicode.GetBytes(res); handler.Send(data); // закрываем сокет handler.Shutdown(SocketShutdown.Both); handler.Close(); }; actionList.Add("add", (prs) => { return(wordDictionary.Add(prs)); }); actionList.Add("get", (prs) => { return(wordDictionary.Get(prs)); }); actionList.Add("delete", (prs) => { return(wordDictionary.Delete(prs)); }); try { // связываем сокет с локальной точкой, по которой будем принимать данные listenSocket.Bind(ipPoint); // начинаем прослушивание listenSocket.Listen(10); Console.WriteLine("Сервер запущен. Ожидание подключений..."); while (true) { Socket socket_client = listenSocket.Accept(); var startNew = Task.Factory.StartNew(proc_action, socket_client); } } catch (Exception ex) { Console.WriteLine(ex.Message); } }
internal LPSocker CreateSocker(Socket socket, ILPPacketParser packetParser, object parent, bool isAcceptCreate) { bool result = false; LPSocker socker = null; if (LOG_ERROR(socket != null)) { goto Exit0; } if (LOG_ERROR(packetParser != null)) { goto Exit0; } socker = new LPSocker(); if (LOG_ERROR(packetParser != null)) { goto Exit0; } socker.ID = _GenerateSockerID(); socker.Sock = socket; socker.Parent = parent; socker.IsAcceptCreate = isAcceptCreate; socker.IsClosed = false; socker.IsSending = false; socker.PacketParser = packetParser; socker.RecvBuf = new LPLoopBuf(); if (LOG_ERROR(socker.RecvBuf != null)) { goto Exit0; } result = socker.RecvBuf.Init(LP.RecvBufSize); if (LOG_ERROR(result)) { goto Exit0; } socker.SendBuf = new LPLoopBuf(); if (LOG_ERROR(socker.SendBuf != null)) { goto Exit0; } result = socker.SendBuf.Init(LP.SendBufSize); if (LOG_ERROR(result)) { goto Exit0; } lock (m_ValidListLocker) { result = m_ValidSockerList.PushRear(socker); if (LOG_ERROR(result)) { goto Exit0; } } return(socker); Exit0: return(null); }
/// <summary> /// @see {@link AbstractNioChannel#AbstractNioChannel(Channel, SelectableChannel, int)} /// </summary> protected AbstractSocketMessageChannel(IChannel parent, Socket socket) : base(parent, socket) { }
private void start_Click(object sender, EventArgs e) { try { String ip = "127.0.0.1"; int port = 9001; int maxBuffer = 100; Console.WriteLine("\nWaiting for connection.."); IPAddress ipAddress = IPAddress.Parse(ip); TcpListener tcpListener = new TcpListener(ipAddress, port); tcpListener.Start(); Thread pinger = new Thread( () => { while (discover) { btnDiscoveryStart_Click(null, null); Thread.Sleep(5000); } }); pinger.Start(); Thread t = new Thread( () => { while (true) { addMessage("Backend Server"); addMessage(">>Listening on socket"); using (socket = tcpListener.AcceptSocket()) { byte[] receiveBuffer = new byte[maxBuffer]; int usedBuffer = socket.Receive(receiveBuffer); String msg = ""; for (int i = 0; i < usedBuffer; i++) { msg += Convert.ToChar(receiveBuffer[i]); } addMessage(">>Received message: " + msg); if (msg.Equals("discover")) { addMessage("Discovery"); btnInviteReq_Click(null, null); tDiscover.Join(); } if (msg.Equals("deploy")) { addMessage("Deployment"); discover = false; tDeploy = new Thread(deployer); tDeploy.Start(); tDeploy.Join(); addMessage("Heartbeat"); tHeartbeat = new Thread(heart); tHeartbeat.Start(); } } } }); t.Start(); } catch (Exception ex) { Console.WriteLine(string.Format("Error: {0}", ex.StackTrace)); } }
protected override void ReviceAcceptSocket(Socket socket) { AddNewClient(new AionConnection(socket)); }
/// <summary> /// 接收的最大值 /// </summary> /// <param name="bufferSize">接收的最大值</param> public StateObject(int bufferSize, Socket socket = null) { BufferSize = bufferSize; Buffer = new byte[bufferSize]; WorkSocket = socket; }
public void NotifyBase(NotifyType notifyType, Socket socket, BaseInfo receiveInfo) { }
private PipelineInstruction QueueOrCreateDataConection(PipelineEntry entry, ResponseDescription response, bool timeout, ref Stream?stream, out bool isSocketReady) { isSocketReady = false; if (_dataHandshakeStarted) { isSocketReady = true; return(PipelineInstruction.Pause); //if we already started then this is re-entering into the callback where we proceed with the stream } _dataHandshakeStarted = true; // Handle passive responses by parsing the port and later doing a Connect(...) bool isPassive = false; int port = -1; if (entry.Command == "PASV\r\n" || entry.Command == "EPSV\r\n") { if (!response.PositiveCompletion) { _abortReason = SR.Format(SR.net_ftp_server_failed_passive, response.Status); return(PipelineInstruction.Abort); } if (entry.Command == "PASV\r\n") { port = GetPortV4(response.StatusDescription !); } else { port = GetPortV6(response.StatusDescription !); } isPassive = true; } if (isPassive) { Debug.Assert(port != -1, "'port' not set."); try { _dataSocket = CreateFtpDataSocket((FtpWebRequest)_request !, Socket); } catch (ObjectDisposedException) { throw ExceptionHelper.RequestAbortedException; } IPEndPoint localEndPoint = new IPEndPoint(((IPEndPoint)Socket.LocalEndPoint !).Address, 0); _dataSocket.Bind(localEndPoint); _passiveEndPoint = new IPEndPoint(ServerAddress, port); } PipelineInstruction result; if (_passiveEndPoint != null) { IPEndPoint passiveEndPoint = _passiveEndPoint; _passiveEndPoint = null; if (NetEventSource.Log.IsEnabled()) { NetEventSource.Info(this, "starting Connect()"); } if (_isAsync) { _dataSocket !.BeginConnect(passiveEndPoint, s_connectCallbackDelegate, this); result = PipelineInstruction.Pause; } else { _dataSocket !.Connect(passiveEndPoint); result = PipelineInstruction.Advance; // for passive mode we end up going to the next command } } else { if (NetEventSource.Log.IsEnabled()) { NetEventSource.Info(this, "starting Accept()"); } if (_isAsync) { _dataSocket !.BeginAccept(s_acceptCallbackDelegate, this); result = PipelineInstruction.Pause; } else { Socket listenSocket = _dataSocket !; try { _dataSocket = _dataSocket !.Accept(); if (!ServerAddress.Equals(((IPEndPoint)_dataSocket.RemoteEndPoint !).Address)) { _dataSocket.Close(); throw new WebException(SR.net_ftp_active_address_different, WebExceptionStatus.ProtocolError); } isSocketReady = true; // for active mode we end up creating a stream before advancing the pipeline result = PipelineInstruction.Pause; } finally { listenSocket.Close(); } } } return(result); }
public User(AsynchronousServerSocket server, Socket socket, ICipher cipher) : base(server, socket, cipher) { m_socket = server; }
public NKC_SocketUDP() { _socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); }
//private const int port = 10100; public Client(int port) { clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); clientSocket.Connect(new IPEndPoint(IPAddress.Loopback, port)); }
/// <summary> /// Raises the <see cref="E:System.Web.UI.Control.Load" /> event. /// </summary> /// <param name="e">The <see cref="T:System.EventArgs" /> object that contains the event data.</param> protected override void OnLoad(EventArgs e) { base.OnLoad(e); if (CurrentWorkflow == null || CurrentCheckInState == null) { NavigateToHomePage(); } else { if (!Page.IsPostBack) { try { lTitle.Text = GetAttributeValue("Title"); string detailMsg = GetAttributeValue("DetailMessage"); var printFromClient = new List <CheckInLabel>(); var printFromServer = new List <CheckInLabel>(); // Print the labels foreach (var family in CurrentCheckInState.CheckIn.Families.Where(f => f.Selected)) { lbAnother.Visible = CurrentCheckInState.CheckInType.TypeOfCheckin == TypeOfCheckin.Individual && family.People.Count > 1; foreach (var person in family.GetPeople(true)) { foreach (var groupType in person.GetGroupTypes(true)) { foreach (var group in groupType.GetGroups(true)) { foreach (var location in group.GetLocations(true)) { foreach (var schedule in location.GetSchedules(true)) { var li = new HtmlGenericControl("li"); li.InnerText = string.Format(detailMsg, person.ToString(), group.ToString(), location.Location.Name, schedule.ToString(), person.SecurityCode); phResults.Controls.Add(li); } } } if (groupType.Labels != null && groupType.Labels.Any()) { printFromClient.AddRange(groupType.Labels.Where(l => l.PrintFrom == Rock.Model.PrintFrom.Client)); printFromServer.AddRange(groupType.Labels.Where(l => l.PrintFrom == Rock.Model.PrintFrom.Server)); } } } } if (printFromClient.Any()) { var urlRoot = string.Format("{0}://{1}", Request.Url.Scheme, Request.Url.Authority); printFromClient .OrderBy(l => l.PersonId) .ThenBy(l => l.Order) .ToList().ForEach(l => l.LabelFile = urlRoot + l.LabelFile.Replace("GetFile.ashx", "NP_GetCheckinLabel.ashx")); printFromClient.Take(printFromClient.Count() - 1).ToList().ForEach(l => { l.LabelFile += "&delaycut=T"; l.LabelKey += "-nocut"; }); AddLabelScript(printFromClient.ToJson()); } if (printFromServer.Any()) { var messages = new List <string>(); Socket socket = null; string currentIp = string.Empty; foreach (var label in printFromServer .OrderBy(l => l.PersonId) .ThenBy(l => l.Order)) { var labelCache = KioskLabel.Get(label.FileGuid); if (labelCache != null) { if (!string.IsNullOrWhiteSpace(label.PrinterAddress)) { if (label.PrinterAddress != currentIp) { if (socket != null && socket.Connected) { socket.Shutdown(SocketShutdown.Both); socket.Close(); } int printerPort = 9100; var printerIpAddress = label.PrinterAddress; // If the user specified in 0.0.0.0:1234 syntax then pull our the IP and port numbers. if (printerIpAddress.Contains(":")) { var segments = printerIpAddress.Split(':'); printerIpAddress = segments[0]; printerPort = segments[1].AsInteger(); } var printerEndpoint = new IPEndPoint(IPAddress.Parse(printerIpAddress), printerPort); socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); IAsyncResult result = socket.BeginConnect(printerEndpoint, null, null); bool success = result.AsyncWaitHandle.WaitOne(5000, true); } string printContent = labelCache.FileContent; foreach (var mergeField in label.MergeFields) { if (!string.IsNullOrWhiteSpace(mergeField.Value)) { printContent = Regex.Replace(printContent, string.Format(@"(?<=\^FD){0}(?=\^FS)", mergeField.Key), mergeField.Value); } else { // Remove the box preceding merge field printContent = Regex.Replace(printContent, string.Format(@"\^FO.*\^FS\s*(?=\^FT.*\^FD{0}\^FS)", mergeField.Key), string.Empty); // Remove the merge field printContent = Regex.Replace(printContent, string.Format(@"\^FD{0}\^FS", mergeField.Key), "^FD^FS"); } } if (label != printFromServer.OrderBy(l => l.Order).LastOrDefault()) { printContent = printContent.Replace("^PQ1,1,1,Y", ""); printContent = printContent.Replace("^XZ", "^XB^XZ"); } if (socket.Connected) { if (socket.Connected) { var ns = new NetworkStream(socket); //var encoder = System.Text.Encoding.GetEncoding( "ISO-8859-1" ); var encoder = System.Text.Encoding.UTF8; byte[] toSend = encoder.GetBytes(printContent); ns.Write(toSend, 0, toSend.Length); } } else { messages.Add("NOTE: Could not connect to printer!"); } } } } // Close the socket if (socket != null && socket.Connected) { socket.Shutdown(SocketShutdown.Both); socket.Close(); } foreach (var message in messages) { phResults.Controls.Add(new LiteralControl(string.Format("<br/>{0}", message))); } } } catch (Exception ex) { LogException(ex); } } } }
protected void WriteResponseStream(Socket client, Stream response, long length, string filename) { WriteResponseStream(client, response, length, filename, 0); }
public TcpClient(Socket socket, IClientData data) { _socket = socket; ClientData = data; }