private void StartListener(IPEndPoint endPoint) { _listener = new TcpListener(endPoint); _listener.Start(5); _log.WriteLine("Server {0} listening", endPoint.Address.ToString()); _listener.AcceptTcpClientAsync().ContinueWith(t => OnAccept(t), TaskScheduler.Default); }
public static void Main() { byte[] data = new byte[1024]; IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 9876); UdpClient newsock = new UdpClient(ipep); Console.WriteLine("Waiting for a client..."); IPEndPoint sender = new IPEndPoint(IPAddress.Any, 9877); data = newsock.Receive(ref sender); Console.WriteLine("Message received from {0}:", sender.ToString()); Console.WriteLine(Encoding.ASCII.GetString(data, 0, data.Length)); string msg = Encoding.ASCII.GetString(data, 0, data.Length); data = Encoding.ASCII.GetBytes(msg); newsock.Send(data, data.Length, sender); while(true){ data = newsock.Receive(ref sender); Console.WriteLine(Encoding.ASCII.GetString(data, 0, data.Length)); newsock.Send(data, data.Length, sender); } }
private static void SendMes(string datagram) { // Создаем UdpClient UdpClient sender = new UdpClient(); // Создаем endPoint по информации об удаленном хосте IPEndPoint endPoint = new IPEndPoint(remoteIPAddress, remotePort); try { // Преобразуем данные в массив байтов byte[] bytes = Encoding.UTF8.GetBytes(datagram); // Отправляем данные sender.Send(bytes, bytes.Length, endPoint); } catch (Exception ex) { Console.WriteLine("Возникло исключение: " + ex.ToString() + "\n " + ex.Message); } finally { // Закрыть соединение sender.Close(); } }
public static int Main() { bool done = false; UdpClient listener = new UdpClient(listenPort); IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, listenPort); string received_data; byte[] receive_byte_array; try { while (!done) { Console.WriteLine("Waiting for broadcast"); // this is the line of code that receives the broadcase message. // It calls the receive function from the object listener (class UdpClient) // It passes to listener the end point groupEP. // It puts the data from the broadcast message into the byte array // named received_byte_array. // I don't know why this uses the class UdpClient and IPEndPoint like this. // Contrast this with the talker code. It does not pass by reference. // Note that this is a synchronous or blocking call. receive_byte_array = listener.Receive(ref groupEP); Console.WriteLine("Received a broadcast from {0}", groupEP.ToString()); received_data = Encoding.ASCII.GetString(receive_byte_array, 0, receive_byte_array.Length); Console.WriteLine("data follows \n{0}\n\n", received_data); } } catch (Exception e) { Console.WriteLine(e.ToString()); } listener.Close(); return 0; }
public SyncClient() { var hostName = Dns.GetHostName(); var localAdd = Dns.GetHostEntry(hostName).AddressList[0]; var localEP = new IPEndPoint(localAdd, 0); TcpClient = new TcpClient(); //new TcpClient(localEP); }
public void DisconnectAsync_Success() { AutoResetEvent completed = new AutoResetEvent(false); IPEndPoint loopback = new IPEndPoint(IPAddress.Loopback, 0); using (var server1 = SocketTestServer.SocketTestServerFactory(SocketImplementationType.Async, loopback)) using (var server2 = SocketTestServer.SocketTestServerFactory(SocketImplementationType.Async, loopback)) { SocketAsyncEventArgs args = new SocketAsyncEventArgs(); args.Completed += OnCompleted; args.UserToken = completed; args.RemoteEndPoint = server1.EndPoint; args.DisconnectReuseSocket = true; using (Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { Assert.True(client.ConnectAsync(args)); completed.WaitOne(); Assert.Equal(SocketError.Success, args.SocketError); Assert.True(client.DisconnectAsync(args)); completed.WaitOne(); Assert.Equal(SocketError.Success, args.SocketError); args.RemoteEndPoint = server2.EndPoint; Assert.True(client.ConnectAsync(args)); completed.WaitOne(); Assert.Equal(SocketError.Success, args.SocketError); } } }
public void init() { IP = "192.168.15.11"; port = 8051; remoteEndPoint = new IPEndPoint(IPAddress.Parse(IP), port); client = new UdpClient(); }
public static void StartListening() { // Data buffer for incoming data. // Establish the local endpoint for the socket. // The DNS name of the computer // running the listener is "host.contoso.com". //IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName()); //IPAddress ipAddress = ipHostInfo.AddressList[0]; IPAddress ipAddress = IPAddress.Parse("127.0.0.1"); IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000); // Create a TCP/IP socket. Socket listener = new Socket(AddressFamily.InterNetwork,SocketType.Stream, ProtocolType.Tcp); // Bind the socket to the local //endpoint and listen for incoming connections. try { listener.Bind(localEndPoint); listener.Listen(100); while (!stop) { // Set the event to nonsignaled state. allDone.Reset(); // Start an asynchronous socket to listen for connections. LogMgr.Log("Waiting for a connection..."); listener.BeginAccept(new AsyncCallback(AcceptCallback),listener); // Wait until a connection is made before continuing. allDone.WaitOne(); } } catch (Exception e) { LogMgr.LogError(e); } }
internal static IPEndPoint[] ParseActiveTcpListenersFromFiles(string tcp4ConnectionsFile, string tcpConnections6File) { string tcp4FileContents = File.ReadAllText(tcp4ConnectionsFile); string[] v4connections = tcp4FileContents.Split(s_newLineSeparator, StringSplitOptions.RemoveEmptyEntries); string tcp6FileContents = File.ReadAllText(tcpConnections6File); string[] v6connections = tcp6FileContents.Split(s_newLineSeparator, StringSplitOptions.RemoveEmptyEntries); IPEndPoint[] endPoints = new IPEndPoint[v4connections.Length + v6connections.Length - 2]; // First line is header in each file int index = 0; // TCP Connections for (int i = 1; i < v4connections.Length; i++) // Skip first line header { string line = v4connections[i]; IPAddress remoteIPAddress; int remotePort; ParseLocalConnectionInformation(line, out remoteIPAddress, out remotePort); endPoints[index++] = new IPEndPoint(remoteIPAddress, remotePort); } // TCP6 Connections for (int i = 1; i < v6connections.Length; i++) // Skip first line header { string line = v6connections[i]; IPAddress remoteIPAddress; int remotePort; ParseLocalConnectionInformation(line, out remoteIPAddress, out remotePort); endPoints[index++] = new IPEndPoint(remoteIPAddress, remotePort); } return endPoints; }
public void Connection() { if(!connected) { string ip = IP.text; Debug.Log("[CLIENT] Connecting to Server [" + ip + ":" + port + "]"); try { IPAddress ipAdress = IPAddress.Parse(ip); IPEndPoint remoteEP = new IPEndPoint(ipAdress, port); PlayerPrefs.SetString ("IP_Address", ip); // Create a TCP/IP socket. client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); // Connect to the remote endpoint. client.BeginConnect( remoteEP, new AsyncCallback(ConnectCallback), client); connectDone.WaitOne(); Receive(client); } catch (Exception e) { distributor.closeConnection(); } } else { Application.Quit(); } }
void Start() { Application.runInBackground = true; Debug.Log("Net listener started!"); // Data buffer for incoming data. bytes = new byte[1024]; // Connect to a remote device. try { // Establish the remote endpoint for the socket. // This example uses port 30303 on the local computer. IPHostEntry ipHostInfo = Dns.GetHostEntry("localhost"); IPAddress ipAddress = ipHostInfo.AddressList[0]; remoteEP = new IPEndPoint(ipAddress, 30303); // Create a TCP/IP socket. socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); socket.Connect(remoteEP); Debug.Log("Socket connected to {0}" + socket.RemoteEndPoint.ToString()); idMap = new Dictionary<int, GameObject>(); socket.Blocking = false; } catch (Exception e) { Debug.Log(e.ToString()); } }
private void exportData(ref UdpClient client, ref IPEndPoint anyIP) { byte[] data; string text; text = "SOT"; // start of table text = text + System.Environment.NewLine; data = System.Text.Encoding.ASCII.GetBytes(text); client.Send(data, data.Length, anyIP); foreach (var ptr in timeGraphScript.dateTime_val_dic) { text = ptr.Key.ToString("yyyy/MM/dd HH:mm:ss"); text = text + ","; text = text + ptr.Value.ToString(); text = text + System.Environment.NewLine; data = System.Text.Encoding.ASCII.GetBytes(text); client.Send(data, data.Length, anyIP); } text = "EOT"; // end of table text = text + System.Environment.NewLine; data = System.Text.Encoding.ASCII.GetBytes(text); client.Send(data, data.Length, anyIP); }
// Use this for initialization void Start() { // Set up Server End Point for sending packets. IPHostEntry serverHostEntry = Dns.GetHostEntry(serverIp); IPAddress serverIpAddress = serverHostEntry.AddressList[0]; serverEndPoint = new IPEndPoint(serverIpAddress, serverPort); Debug.Log("Server IPEndPoint: " + serverEndPoint.ToString()); // Set up Client End Point for receiving packets. IPHostEntry clientHostEntry = Dns.GetHostEntry(Dns.GetHostName()); IPAddress clientIpAddress = IPAddress.Any; foreach (IPAddress ip in clientHostEntry.AddressList) { if (ip.AddressFamily == AddressFamily.InterNetwork) { clientIpAddress = ip; } } clientEndPoint = new IPEndPoint(clientIpAddress, serverPort); Debug.Log("Client IPEndPoint: " + clientEndPoint.ToString()); // Create socket for client and bind to Client End Point (Ip/Port). clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); try { clientSocket.Bind(clientEndPoint); } catch (Exception e) { Debug.Log("Winsock error: " + e.ToString()); } }
// Creates a new instance of the UdpClient class that communicates on the // specified port number. public UdpClient(int port, AddressFamily family) { // Validate input parameters. if (!TcpValidationHelpers.ValidatePortNumber(port)) { throw new ArgumentOutOfRangeException("port"); } // Validate the address family. if (family != AddressFamily.InterNetwork && family != AddressFamily.InterNetworkV6) { throw new ArgumentException(SR.net_protocol_invalid_family, "family"); } IPEndPoint localEP; _family = family; if (_family == AddressFamily.InterNetwork) { localEP = new IPEndPoint(IPAddress.Any, port); } else { localEP = new IPEndPoint(IPAddress.IPv6Any, port); } CreateClientSocket(); _clientSocket.Bind(localEP); }
private void ReceiveData() { client = new UdpClient(8000); while (running) { try { IPEndPoint anyIP = new IPEndPoint(IPAddress.Any, 0); byte[] data = client.Receive(ref anyIP); string text = Encoding.UTF8.GetString(data); Debug.Log("Input "+text); string[] info = text.Split(':'); inputText = text; if(info[0].Equals("speed")){ speed= info[1]; } if(info[0].Equals("turn")){ axis= info[1]; } } catch (Exception err) { running =false; print(err.ToString()); } } }
private void Receive(IAsyncResult ar) { IPEndPoint ip = new IPEndPoint(IPAddress.Any, 15000); byte[] bytes = udp.EndReceive(ar, ref ip); string message = Encoding.ASCII.GetString(bytes); StartListening(); }
void Connect() { Debug.Log ("Connect"); //if (clientSocket != null && clientSocket.Connected) Disconnect(); //var ipAddress = Dns.GetHostAddresses ("localhost"); //IPEndPoint ipEndPoint = new IPEndPoint(ipAddress[0], 1234); IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Parse(hostIp), port); // Create Socket AddressFamily family = AddressFamily.InterNetwork; SocketType sokType = SocketType.Stream; ProtocolType proType = ProtocolType.Tcp; clientSocket = new Socket(family, sokType, proType); Debug.Log("Connecting to localhost"); clientSocket.Connect (ipEndPoint); // arriving here means the operation completed asyncConnect.IsCompleted = true) // but not necessarily successfully if (clientSocket.Connected == false) { Debug.Log(".client is not connected."); return; } Debug.Log(".client is connected."); clientSocket.Blocking = false; }
public void Success() { if (Socket.OSSupportsIPv4) { using (Socket receiver = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)) { int port = receiver.BindToAnonymousPort(IPAddress.Loopback); receiver.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.PacketInformation, true); Socket sender = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); sender.Bind(new IPEndPoint(IPAddress.Loopback, 0)); sender.SendTo(new byte[1024], new IPEndPoint(IPAddress.Loopback, port)); IPPacketInformation packetInformation; SocketFlags flags = SocketFlags.None; EndPoint remoteEP = new IPEndPoint(IPAddress.Any, 0); int len = receiver.ReceiveMessageFrom(new byte[1024], 0, 1024, ref flags, ref remoteEP, out packetInformation); Assert.Equal(1024, len); Assert.Equal(sender.LocalEndPoint, remoteEP); Assert.Equal(((IPEndPoint)sender.LocalEndPoint).Address, packetInformation.Address); sender.Dispose(); } } }
internal static IPEndPoint[] ParseActiveTcpListenersFromFiles(string tcp4ConnectionsFile, string tcp6ConnectionsFile) { if (!File.Exists(tcp4ConnectionsFile) || !File.Exists(tcp6ConnectionsFile)) { throw new PlatformNotSupportedException(SR.net_InformationUnavailableOnPlatform); } string tcp4FileContents = File.ReadAllText(tcp4ConnectionsFile); string[] v4connections = tcp4FileContents.Split(s_newLineSeparator, StringSplitOptions.RemoveEmptyEntries); string tcp6FileContents = File.ReadAllText(tcp6ConnectionsFile); string[] v6connections = tcp6FileContents.Split(s_newLineSeparator, StringSplitOptions.RemoveEmptyEntries); /// First line is header in each file. IPEndPoint[] endPoints = new IPEndPoint[v4connections.Length + v6connections.Length - 2]; int index = 0; // TCP Connections for (int i = 1; i < v4connections.Length; i++) // Skip first line header. { string line = v4connections[i]; IPEndPoint endPoint = ParseLocalConnectionInformation(line); endPoints[index++] = endPoint; } // TCP6 Connections for (int i = 1; i < v6connections.Length; i++) // Skip first line header. { string line = v6connections[i]; IPEndPoint endPoint = ParseLocalConnectionInformation(line); endPoints[index++] = endPoint; } return endPoints; }
void RecieveDatagram() { UdpClient receivingUdpClient = new UdpClient ( 35143 ); IPEndPoint RemoteIpEndPoint = new IPEndPoint ( IPAddress.Any, 0 ); while ( true ) { try { Byte[] receiveBytes = receivingUdpClient.Receive ( ref RemoteIpEndPoint ); returnData = Encoding.Unicode.GetString ( receiveBytes ); if ( returnData.Substring ( 0, 17 ) == "[2CatStudios:UMP]" ) { UnityEngine.Debug.Log ( "Recieved '" + returnData.ToString () + "' This message was sent on " + RemoteIpEndPoint.Address.ToString() + " via the port " + RemoteIpEndPoint.Port.ToString ()); returnData = returnData.Substring ( 17 ); } else { UnityEngine.Debug.Log ( "Data was recieved, but it was not expected." ); } } catch ( Exception e ) { UnityEngine.Debug.Log ( e.ToString ()); returnData = e.ToString (); } } }
void procComm() { port = getPort(); string ipadr = getIpadr (); client = new UdpClient (); // send string sendstr = IFmsg.text + System.Environment.NewLine; byte[] data = ASCIIEncoding.ASCII.GetBytes (sendstr); client.Send (data, data.Length, ipadr, port); // receive client.Client.ReceiveTimeout = 2000; // msec IPEndPoint remoteIP = new IPEndPoint(IPAddress.Any, 0); lastRcvd = ""; try { data = client.Receive (ref remoteIP); if (data.Length > 0) { string text = Encoding.ASCII.GetString (data); lastRcvd = text; } } catch (Exception err) { } client.Close (); }
public static bool Connect(IPEndPoint remoteEndPoint, int timeoutMSec) { TimeoutObject.Reset(); socketexception = null; string serverip = Convert.ToString(remoteEndPoint.Address); int serverport = remoteEndPoint.Port; TcpClient tcpclient = new TcpClient(); tcpclient.BeginConnect(serverip, serverport, new AsyncCallback(CallBackMethod), tcpclient); if (TimeoutObject.WaitOne(timeoutMSec, false)) { if (IsConnectionSuccessful) { tcpclient.Close(); return true; } else { tcpclient.Close(); return false; } } else { tcpclient.Close(); return false; } }
public void LoadClient() { client = new UdpClient(System.Convert.ToInt32(port)); receivePoint = new IPEndPoint(IPAddress.Parse(ip),System.Convert.ToInt32(port)); Thread startClient = new Thread(new ThreadStart(start_client)); startClient.Start(); }
public void SelectRead_Multiple_Success() { using (var firstReceiver = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)) using (var secondReceiver = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)) using (var sender = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)) { int firstReceiverPort = firstReceiver.BindToAnonymousPort(IPAddress.Loopback); var firstReceiverEndpoint = new IPEndPoint(IPAddress.Loopback, firstReceiverPort); int secondReceiverPort = secondReceiver.BindToAnonymousPort(IPAddress.Loopback); var secondReceiverEndpoint = new IPEndPoint(IPAddress.Loopback, secondReceiverPort); sender.SendTo(new byte[1], SocketFlags.None, firstReceiverEndpoint); sender.SendTo(new byte[1], SocketFlags.None, secondReceiverEndpoint); var sw = Stopwatch.StartNew(); Assert.True(SpinWait.SpinUntil(() => { var list = new List<Socket> { firstReceiver, secondReceiver }; Socket.Select(list, null, null, Math.Max((int)(SelectSuccessTimeoutMicroseconds - (sw.Elapsed.TotalSeconds * 1000000)), 0)); Assert.True(list.Count <= 2); if (list.Count == 2) { Assert.Equal(firstReceiver, list[0]); Assert.Equal(secondReceiver, list[1]); return true; } return false; }, SelectSuccessTimeoutMicroseconds / 1000), "Failed to select both items within allotted time"); } }
public void Start(int port) { if (listener != null && listener.Server.IsBound) { return; } this.port = port; IPEndPoint ipEnd = new IPEndPoint(IPAddress.Any, port); listener = new TcpListener(ipEnd); try { listener.Start(); running = true; if (LOGGER.IsInfoEnabled) { LOGGER.Info("Push Server Simulator is successfully started on port " + port.ToString()); } } catch (Exception e) { if (LOGGER.IsErrorEnabled) { LOGGER.Error("Error occured while trying to start Push Server Simulator on port " + port.ToString() + " . Message: " + e.Message); } } thread = new Thread(new ThreadStart(listen)); thread.Start(); }
public UDPServer() { try { // Iniciando array de clientes conectados this.listaClientes = new ArrayList(); entrantPackagesCounter = 0; sendingPackagesCounter = 0; // Inicializando el delegado para actualizar estado //this.updateStatusDelegate = new UpdateStatusDelegate(this.UpdateStatus); // Inicializando el socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); // Inicializar IP y escuhar puerto 30000 IPEndPoint server = new IPEndPoint(IPAddress.Any, 30001); // Asociar socket con el IP dado y el puerto serverSocket.Bind(server); // Inicializar IPEndpoint de los clientes IPEndPoint clients = new IPEndPoint(IPAddress.Any, 0); // Inicializar Endpoint de clientes EndPoint epSender = (EndPoint)clients; // Empezar a escuhar datos entrantes serverSocket.BeginReceiveFrom(this.dataStream, 0, this.dataStream.Length, SocketFlags.None, ref epSender, new AsyncCallback(ReceiveData), epSender); } catch (Exception ex) { //Debug.Log("Error al cargar servidor: " + ex.Message+ " ---UDP "); } }
public bool Connect() { try { serverRemote = new IPEndPoint(IPAddress.Parse(ipAddress), portNumber); udpClient = new UdpClient(); udpClient.Connect(serverRemote); if(udpClient.Client.Connected) { Debug.Log("connected!"); sendUDPPacket("ANYONE OUT THERE?"); //byte[] data = Encoding.UTF8.GetBytes(toSend); //client.Send(data, data.Length, serverRemote); //client.SendTimeout(serverRemote, data); } } catch(Exception ex) { print ( ex.Message + " : OnConnect"); } isConnected = true; if ( udpClient == null ) return false; return udpClient.Client.Connected; }
Socket ConnectSocket(string server, int port) { Socket s = null; IPHostEntry hostEntry = null; // Get host related information. hostEntry = Dns.GetHostEntry(server); // 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) { IPEndPoint ipe = new IPEndPoint(address, port); Socket tempSocket = new Socket(ipe.AddressFamily, SocketType.Stream, ProtocolType.Tcp); tempSocket.Connect(ipe); if(tempSocket.Connected) { s = tempSocket; break; } else { continue; } } return s; }
void ConnectToServer() { clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //服务器IP地址 IPAddress ip = IPAddress.Parse(ipaddress); //服务器端口 IPEndPoint ipEndpoint = new IPEndPoint(ip, port); // clientSocket.Connect(new IPEndPoint(IPAddress.Parse(ipaddress), port)); //这是一个异步的建立连接,当连接建立成功时调用connectCallback方法 IAsyncResult result = clientSocket.BeginConnect(ipEndpoint, new AsyncCallback(connectCallback), clientSocket); //这里做一个超时的监测,当连接超过5秒还没成功表示超时 bool success = result.AsyncWaitHandle.WaitOne(5000, true); if (!success) { //超时 //Closed(); Debug.Log("connect Time Out"); } else { //与socket建立连接成功,开启线程接受服务端数据。 //worldpackage = new List<JFPackage.WorldPackage>(); //Thread thread = new Thread(new ThreadStart(ReceiveSorket)); t = new Thread(RecevieMessage); t.IsBackground = true; t.Start(); } }
public Byte[] Receive(ref IPEndPoint remoteEP) { Contract.Ensures(Contract.Result<Byte[]>() != null); Contract.Ensures(Contract.Result<Byte[]>().Length > 0); // after reading the code return default(Byte[]); }
public void Start(int connectionTimeout = 10000) { if (_process != null) return; string password; { byte[] buffer = new byte[32]; _rnd.GetBytes(buffer); password = BitConverter.ToString(buffer).Replace("-", "").ToLower(); } string dataDir = Path.Combine(Path.GetDirectoryName(_torExecutableFilePath), "data"); if (!Directory.Exists(dataDir)) Directory.CreateDirectory(dataDir); string arguments = "--DataDirectory \"" + dataDir + "\" --controlport " + _controlPort + " --HashedControlPassword " + HashPassword(password); if (_Socks5EP == null) _Socks5EP = new IPEndPoint(IPAddress.Loopback, 9050); //default else arguments += " --SocksPort " + _Socks5EP.ToString(); switch (_proxyType) { case TorProxyType.Http: arguments += " --HTTPProxy " + _proxyHost + (_proxyPort == 0 ? "" : ":" + _proxyPort); if (_proxyCredential != null) arguments += " --HTTPProxyAuthenticator " + _proxyCredential.UserName + ":" + _proxyCredential.Password; break; case TorProxyType.Https: arguments += " --HTTPSProxy " + _proxyHost + (_proxyPort == 0 ? "" : ":" + _proxyPort); if (_proxyCredential != null) arguments += " --HTTPSProxyAuthenticator " + _proxyCredential.UserName + ":" + _proxyCredential.Password; break; case TorProxyType.Socks4: arguments += " --Socks4Proxy " + _proxyHost + (_proxyPort == 0 ? "" : ":" + _proxyPort); break; case TorProxyType.Socks5: arguments += " --Socks5Proxy " + _proxyHost + (_proxyPort == 0 ? "" : ":" + _proxyPort); if (_proxyCredential != null) { arguments += " --Socks5ProxyUsername " + _proxyCredential.UserName; arguments += " --Socks5ProxyPassword " + _proxyCredential.Password; } break; } ProcessStartInfo processInfo = new ProcessStartInfo(_torExecutableFilePath, arguments); processInfo.UseShellExecute = false; processInfo.CreateNoWindow = true; Process process = Process.Start(processInfo); Thread.Sleep(2000); //wait for process to start int retry = 1; while (true) { try { _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); _socket.ReceiveTimeout = 10000; _socket.SendTimeout = 10000; IAsyncResult result = _socket.BeginConnect(IPAddress.Loopback, _controlPort, null, null); if (!result.AsyncWaitHandle.WaitOne(connectionTimeout)) throw new SocketException((int)SocketError.TimedOut); if (!_socket.Connected) throw new SocketException((int)SocketError.ConnectionRefused); NetworkStream stream = new NetworkStream(_socket); _sR = new StreamReader(stream); _sW = new StreamWriter(stream); _sW.AutoFlush = true; _sW.WriteLine("AUTHENTICATE \"" + password + "\""); string response = _sR.ReadLine(); if (!response.StartsWith("250 ")) throw new TorControllerException("Authentication failed: " + response); _sW.WriteLine("SETCONF __OwningControllerProcess=" + Process.GetCurrentProcess().Id); response = _sR.ReadLine(); if (!response.StartsWith("250 ")) throw new TorControllerException("Server returned: " + response); _sW.WriteLine("TAKEOWNERSHIP"); response = _sR.ReadLine(); if (!response.StartsWith("250 ")) throw new TorControllerException("Server returned: " + response); _process = process; break; } catch { if (_socket != null) _socket.Dispose(); if (retry < 3) { retry++; Thread.Sleep(1000); //wait before retrying } else { try { process.Kill(); } catch { } throw; } } } }
public bool connect() { if (m_thread.GetHashCode() % filter == 0) { Console.WriteLine("线程哈希码==" + m_thread.GetHashCode()); } byte[] RelayCmd = new byte[14]; RelayCmd[0] = 170; RelayCmd[1] = 1; RelayCmd[2] = 250; RelayCmd[3] = 250; RelayCmd[4] = 250; RelayCmd[5] = 250; RelayCmd[6] = 250; RelayCmd[7] = 250; RelayCmd[8] = 250; RelayCmd[9] = 250; RelayCmd[10] = 250; RelayCmd[11] = 250; RelayCmd[12] = 250; RelayCmd[13] = 13; for (int i = 0; i < buffer.Length; i++) { RelayCmd[2 + i] = (byte)buffer.ElementAt(i); } int sum = 0; for (int i = 1; i <= 11; i++) { sum += RelayCmd[i]; } sum &= 255; RelayCmd[12] = (byte)sum; try { IPAddress ip = IPAddress.Parse(serverIP); IPEndPoint ipe = new IPEndPoint(ip, port); clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); clientSocket.Connect(ipe); clientSocket.Send(RelayCmd); //receive message string recStr = ""; byte[] recBytes = new byte[4096]; int bytes = clientSocket.Receive(recBytes, recBytes.Length, 0); recStr += "" + recBytes[0] + recBytes[1] + recBytes[2]; if (m_thread.GetHashCode() % filter == 0) { Console.WriteLine(recStr); } } catch (Exception ex) { Console.WriteLine("exception:" + ex.ToString()); return(false); } return(true); }
private string GetServerIp() { IPEndPoint serverIp = (IPEndPoint)client.Client.RemoteEndPoint; return(serverIp.ToString()); }
public Task Abort(IPEndPoint endPoint, string name, UserCredentials userCredentials = null) { return(SendPost(endPoint.ToHttpUrl("/projection/{0}/command/abort", name), string.Empty, userCredentials, HttpStatusCode.OK)); }
/// <summary> /// Gets the connection for a certain remote endpoint. /// </summary> public NetConnection?GetConnection(IPEndPoint endPoint) { TryGetConnection(endPoint, out var connection); return(connection); }
/// <summary> /// Obtains IP address and srNeighbor port from the server's network identifier. /// </summary> /// <param name="NetworkId">Network identifer of the server.</param> /// <param name="NotFound">If the function fails, this is set to true if the reason for failure was that the remote server was not found.</param> /// <param name="IgnoreDbPortValue">If set to true, the function will ignore SrNeighborPort value of the server even if it is set in the database /// and will contact the server on its primary port and then update SrNeighborPort in the database, if it successfully gets its value.</param> /// <returns>End point description or null if the function fails.</returns> public async Task <IPEndPoint> GetServerContactAsync(byte[] NetworkId, StrongBox <bool> NotFound, bool IgnoreDbPortValue = false) { log.Trace("(NetworkId:'{0}',IgnoreDbPortValue:{1})", NetworkId.ToHex(), IgnoreDbPortValue); IPEndPoint res = null; DatabaseLock lockObject = null; bool unlock = false; try { T remoteServer = (await GetAsync(n => n.NetworkId == NetworkId)).FirstOrDefault(); if (remoteServer != null) { log.Trace("{0} server found in the database.", remoteServer is Neighbor ? "Neighbor" : "Follower"); IPAddress addr = new IPAddress(remoteServer.IpAddress); if (!IgnoreDbPortValue && (remoteServer.SrNeighborPort != null)) { res = new IPEndPoint(addr, remoteServer.SrNeighborPort.Value); } else { NeighborhoodActionProcessor neighborhoodActionProcessor = (NeighborhoodActionProcessor)Base.ComponentDictionary[NeighborhoodActionProcessor.ComponentName]; // We do not know srNeighbor port of this server yet (or we ignore it), we have to connect to its primary port and get that information. int srNeighborPort = await neighborhoodActionProcessor.GetServerRolePortFromPrimaryPort(addr, remoteServer.PrimaryPort, ServerRoleType.SrNeighbor); if (srNeighborPort != 0) { lockObject = GetTableLock(); await unitOfWork.AcquireLockAsync(lockObject); unlock = true; remoteServer.SrNeighborPort = srNeighborPort; Update(remoteServer); if (!await unitOfWork.SaveAsync()) { log.Error("Unable to save new srNeighbor port information {0} of {1} ID '{2}' to the database.", srNeighborPort, remoteServer is Neighbor ? "neighbor" : "follower", NetworkId.ToHex()); } res = new IPEndPoint(addr, srNeighborPort); } else { log.Debug("Unable to obtain srNeighbor port from primary port of {0} ID '{1}'.", remoteServer is Neighbor ? "neighbor" : "follower", NetworkId.ToHex()); } } } else { log.Error("Unable to find {0} ID '{1}' in the database.", remoteServer is Neighbor ? "neighbor" : "follower", NetworkId.ToHex()); NotFound.Value = true; } } catch (Exception e) { log.Error("Exception occurred: {0}", e.ToString()); } if (unlock) { unitOfWork.ReleaseLock(lockObject); } log.Trace("(-):{0}", res != null ? res.ToString() : "null"); return(res); }
/// <summary> /// Prepares the report file SSRIncentiveSheet.txt for printing. /// </summary> protected void BtnPrint_Click(object sender, System.EventArgs e) { byte[] bytes = new byte[1024]; // Connect to a remote device. try { if (View == 1) { makingReport(); } else { MessageBox.Show("Please Click The View Button Fisrt"); return; } // Establish the remote endpoint for the socket. // The name of the // remote device is "host.contoso.com". IPHostEntry ipHostInfo = Dns.Resolve("127.0.0.1"); IPAddress ipAddress = ipHostInfo.AddressList[0]; IPEndPoint remoteEP = new IPEndPoint(ipAddress, 62000); // Create a TCP/IP socket. Socket sender1 = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); // Connect the socket to the remote endpoint. Catch any errors. try { sender1.Connect(remoteEP); Console.WriteLine("Socket connected to {0}", sender1.RemoteEndPoint.ToString()); CreateLogFiles.ErrorLog("Form:MechanicReport.aspx,Class:PetrolPumpClass.cs,Method:btnprint_Clickt SSRIncentiveSheet Report Printed" + " userid " + uid); // Encode the data string into a byte array. string home_drive = Environment.SystemDirectory; home_drive = home_drive.Substring(0, 2); byte[] msg = Encoding.ASCII.GetBytes(home_drive + "\\Inetpub\\wwwroot\\Servosms\\Sysitem\\ServosmsPrintServices\\ReportView\\SSRIncentiveSheet.txt<EOF>"); // Send the data through the socket. int bytesSent = sender1.Send(msg); // Receive the response from the remote device. int bytesRec = sender1.Receive(bytes); Console.WriteLine("Echoed test = {0}", Encoding.ASCII.GetString(bytes, 0, bytesRec)); // Release the socket. sender1.Shutdown(SocketShutdown.Both); sender1.Close(); } catch (ArgumentNullException ane) { Console.WriteLine("ArgumentNullException : {0}", ane.ToString()); CreateLogFiles.ErrorLog("Form:SSRIncentiveSheet.aspx,Class:PetrolPumpClass.cs,Method:btnprint_Clickt SSRIncentiveSheet Report Printed" + " EXCEPTION " + ane.Message + " userid " + uid); } catch (SocketException se) { Console.WriteLine("SocketException : {0}", se.ToString()); CreateLogFiles.ErrorLog("Form:SSRIncentiveSheet.aspx,Class:PetrolPumpClass.cs,Method:btnprint_Clickt SSRIncentiveSheet Report Printed" + " EXCEPTION " + se.Message + " userid " + uid); } catch (Exception es) { Console.WriteLine("Unexpected exception : {0}", es.ToString()); CreateLogFiles.ErrorLog("Form:SSRIncentiveSheet.aspx,Class:PetrolPumpClass.cs,Method:btnprint_Clickt SSRIncentiveSheet Report Printed" + " EXCEPTION " + es.Message + " userid " + uid); } } catch (Exception ex) { CreateLogFiles.ErrorLog("Form:SSRIncentiveSheet.aspx,Class:PetrolPumpClass.cs,Method:btnprint_Clickt SSRIncentiveSheet Report Printed" + " EXCEPTION " + ex.Message + " userid " + uid); } }
public static void ConnectionClosed(IPEndPoint endpoint, string data) { Logging.Log("[RECEIVED] Connection closing."); CloseConnection(endpoint); }
public static void KeepAlive(IPEndPoint endpoint, string data) { Logging.Log("Keep alive request."); }
public static void ConnectionStart(IPEndPoint endpoint, string data) { SendMessage(endpoint, ENetID.ID_RequestPassword); }
public DhtListener(IPEndPoint endpoint) : base(endpoint) { }
public TorHiddenServiceInfo CreateHiddenService(int virtualPort, string privateKey, IPEndPoint localHiddenEP = null, string clientBasicAuthUser = null, string clientBasicAuthCookie = null) { _sW.WriteLine("ADD_ONION " + privateKey + (clientBasicAuthUser == null ? "" : " Flags=BasicAuth") + " Port=" + virtualPort + (localHiddenEP == null ? "" : "," + localHiddenEP.ToString()) + (clientBasicAuthUser == null ? "" : " ClientAuth=" + clientBasicAuthUser + ":" + (clientBasicAuthCookie == null ? "" : ":" + clientBasicAuthCookie))); return new TorHiddenServiceInfo(_sR); }
public SocketClient(IPEndPoint serverIpEndPoint) { _serverIpAddress = serverIpEndPoint.Address; _serverPort = serverIpEndPoint.Port; }
protected override void OnMessageReceived(byte[] buffer, IPEndPoint endpoint) { MessageReceived h = MessageReceived; if (h != null) h(buffer, endpoint); }
public TcpSenderPipe(IPAddress address, int port) { this.endpoint = new IPEndPoint(address, port); this.RenewClient(); }
public Server(IPEndPoint endpoint, ServerSettings settings, ModData modData, bool dedicated) { Log.AddChannel("server", "server.log"); listener = new TcpListener(endpoint); listener.Start(); var localEndpoint = (IPEndPoint)listener.LocalEndpoint; Ip = localEndpoint.Address; Port = localEndpoint.Port; Dedicated = dedicated; Settings = settings; Settings.Name = OpenRA.Settings.SanitizedServerName(Settings.Name); ModData = modData; randomSeed = (int)DateTime.Now.ToBinary(); if (UPnP.Status == UPnPStatus.Enabled) { UPnP.ForwardPort(Settings.ListenPort, Settings.ExternalPort).Wait(); } foreach (var trait in modData.Manifest.ServerTraits) { serverTraits.Add(modData.ObjectCreator.CreateObject <ServerTrait>(trait)); } LobbyInfo = new Session { GlobalSettings = { RandomSeed = randomSeed, Map = settings.Map, ServerName = settings.Name, EnableSingleplayer = settings.EnableSingleplayer || !dedicated, GameUid = Guid.NewGuid().ToString() } }; new Thread(_ => { foreach (var t in serverTraits.WithInterface <INotifyServerStart>()) { t.ServerStarted(this); } Log.Write("server", "Initial mod: {0}", ModData.Manifest.Id); Log.Write("server", "Initial map: {0}", LobbyInfo.GlobalSettings.Map); var timeout = serverTraits.WithInterface <ITick>().Min(t => t.TickTimeout); for (;;) { var checkRead = new List <Socket>(); if (State == ServerState.WaitingPlayers) { checkRead.Add(listener.Server); } checkRead.AddRange(Conns.Select(c => c.Socket)); checkRead.AddRange(PreConns.Select(c => c.Socket)); if (checkRead.Count > 0) { Socket.Select(checkRead, null, null, timeout); } if (State == ServerState.ShuttingDown) { EndGame(); break; } foreach (var s in checkRead) { if (s == listener.Server) { AcceptConnection(); continue; } var preConn = PreConns.SingleOrDefault(c => c.Socket == s); if (preConn != null) { preConn.ReadData(this); continue; } var conn = Conns.SingleOrDefault(c => c.Socket == s); if (conn != null) { conn.ReadData(this); } } foreach (var t in serverTraits.WithInterface <ITick>()) { t.Tick(this); } if (State == ServerState.ShuttingDown) { EndGame(); if (UPnP.Status == UPnPStatus.Enabled) { UPnP.RemovePortForward().Wait(); } break; } } foreach (var t in serverTraits.WithInterface <INotifyServerShutdown>()) { t.ServerShutdown(this); } PreConns.Clear(); Conns.Clear(); try { listener.Stop(); } catch { } }) { IsBackground = true }.Start(); }
} // constructor public DvbStpStreamClient(IPEndPoint endpoint) : base(endpoint.Address, endpoint.Port) { // no op } // constructor
/// <summary> /// The thread loop used to actually communicate with the camera. It will attempt to /// continually reconnect with the camera if the connection fails. /// </summary> public void HikEventClient(IPAddress ipAddress, int port, string username, string password) { // Data buffer for incoming data. const int bufferSizeMax = 2048; var byteBuffer = new byte[bufferSizeMax]; // Connect to a remote device. try { // set the status to unknown until connected this.SetDeviceStatus(CameraStatus.Unknown); // Establish the remote endpoint for the socket. var remoteEP = new IPEndPoint(ipAddress, port); var authenticationStr = Base64Encode(username + ":" + password); while (true) { try { switch (this.cameraState) { case CameraState.Start: { // Create a TCP/IP socket. this.buffer = string.Empty; this.sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); // Begin the connection. This will end either with an exception or a callback. this.sock.BeginConnect(remoteEP, new AsyncCallback(this.ConnectCallback), this); this.cameraState = CameraState.Connect; break; } case CameraState.Connect: { // Wait for connection Thread.Sleep(100); break; } case CameraState.Send: { Log.Info("Connected to camera"); // Encode the data string into a byte array. var header = "GET /Event/notification/alertStream HTTP/1.1\r\n" + "Authorization: Basic " + authenticationStr + "\r\n" + "Connection: keep-alive\r\n" + "\r\n"; // Send the data to start the alert stream var bytesSent = this.sock.Send(Encoding.ASCII.GetBytes(header)); this.cameraState = CameraState.Receive; this.lastAlertMsg = DateTime.Now; break; } case CameraState.Receive: { // Wait on the socket for data var readList = new ArrayList {this.sock}; Socket.Select(readList, null, null, 5000); if (this.sock.Available > 0) { // add new data to the buffer var length = this.sock.Receive(byteBuffer); this.buffer += System.Text.Encoding.UTF8.GetString(byteBuffer, 0, length); this.ProcessBuffer(); } // Check if too long between messages var span = DateTime.Now - this.lastAlertMsg; if (span.TotalMilliseconds > 2000) { // Attempt to reconnect Log.Info(span.TotalMilliseconds + " ms since last message. Attempt to reconnect."); this.sock.Shutdown(SocketShutdown.Both); this.sock.Close(); this.cameraState = CameraState.Wait; // status is unknown this.SetDeviceStatus(CameraStatus.Unknown); } break; } case CameraState.Wait: { Thread.Sleep(100); this.cameraState = CameraState.Start; break; } } } catch (SocketException se) { Log.Info("Socket exception: " + se); if (this.sock.Connected) { this.sock.Shutdown(SocketShutdown.Both); this.sock.Close(); } this.cameraState = CameraState.Start; Thread.Sleep(100); } } } catch (Exception e) { Log.Info("Unexpected Exception : " + e); } // reset the status to unknown when exiting this.SetDeviceStatus(CameraStatus.Unknown); }
public responseCode serverProcessHandshake(IPEndPoint clientEndPoint) { throw new NotImplementedException("LOL NOOB"); }
} // constructor public DvbStpStreamClient(IPEndPoint endpoint, CancellationToken cancellationToken) : base(endpoint.Address, endpoint.Port, cancellationToken) { // no op } // constructor
public void Connect(IPEndPoint _endPoint) { endPoint = _endPoint; }
public void sendMessageToEndPoint(Socket socket, IPEndPoint receiver, TCPCopycatPacket packet, TCPCopycatReceiveMessageCallback callbackLambda, int timeoutTime = 1000) { sendMessageToEndPoint(socket, receiver, packet); }
/// <summary> /// Send raw bytes; only used for debugging. /// </summary> public NetSocketResult RawSend(byte[] buffer, int offset, int length, IPEndPoint destination) { // wrong thread might crash with network thread Array.Copy(buffer, offset, _sendBuffer, 0, length); return(SendPacket(length, destination, 1)); }
public void Disconnect() { endPoint = null; }
/// <summary> /// 为请求准备参数 /// </summary> ///<param name="item">参数列表</param> private void SetRequest(HttpItem item) { // 验证证书 SetCer(item); if (item.IPEndPoint != null) { _IPEndPoint = item.IPEndPoint; //设置本地的出口ip和端口 request.ServicePoint.BindIPEndPointDelegate = new BindIPEndPoint(BindIPEndPointCallback); } //设置Header参数 if (item.Header != null && item.Header.Count > 0) { foreach (string key in item.Header.AllKeys) { request.Headers.Add(key, item.Header[key]); } } // 设置代理 SetProxy(item); if (item.ProtocolVersion != null) { request.ProtocolVersion = item.ProtocolVersion; } request.ServicePoint.Expect100Continue = item.Expect100Continue; //请求方式Get或者Post request.Method = item.Method; request.Timeout = item.Timeout; request.KeepAlive = item.KeepAlive; request.ReadWriteTimeout = item.ReadWriteTimeout; if (!string.IsNullOrWhiteSpace(item.Host)) { request.Host = item.Host; } if (item.IfModifiedSince != null) { request.IfModifiedSince = Convert.ToDateTime(item.IfModifiedSince); } //Accept request.Accept = item.Accept; //ContentType返回类型 request.ContentType = item.ContentType; //UserAgent客户端的访问类型,包括浏览器版本和操作系统信息 request.UserAgent = item.UserAgent; // 编码 encoding = item.Encoding; //设置安全凭证 request.Credentials = item.ICredentials; //设置Cookie SetCookie(item); //来源地址 request.Referer = item.Referer; //是否执行跳转功能 request.AllowAutoRedirect = item.Allowautoredirect; if (item.MaximumAutomaticRedirections > 0) { request.MaximumAutomaticRedirections = item.MaximumAutomaticRedirections; } //设置Post数据 SetPostData(item); //设置最大连接 if (item.Connectionlimit > 0) { request.ServicePoint.ConnectionLimit = item.Connectionlimit; } }
/// <summary> /// 通过设置这个属性,可以在发出连接的时候绑定客户端发出连接所使用的IP地址。 /// </summary> /// <param name="servicePoint"></param> /// <param name="remoteEndPoint"></param> /// <param name="retryCount"></param> /// <returns></returns> private IPEndPoint BindIPEndPointCallback(ServicePoint servicePoint, IPEndPoint remoteEndPoint, int retryCount) { return(_IPEndPoint);//端口号 }
public static async void StartListening() { while (true) { Console.WriteLine("Searching for load..."); IPAddress load_address = null; while (true) { try { load_address = KEL103Tools.FindLoadAddress(); break; } catch (Exception ex) { Console.WriteLine("Error searching for load. Retry in 30 seconds."); await Task.Delay(30 * 1000); } } Console.WriteLine("Load found at " + load_address.ToString() + "."); // Data buffer for incoming data. byte[] bytes = new Byte[1024]; IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName()); IPAddress ipAddress = ipHostInfo.AddressList.Where(x => x.AddressFamily == AddressFamily.InterNetwork).ToArray()[0]; Console.WriteLine("My IP is " + ipAddress.ToString()); IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 5025); // Bind the socket to the local endpoint and // listen for incoming connections. try { // Create a TCP/IP socket. using (Socket listener = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp)) { listener.Bind(localEndPoint); listener.Listen(10); using (Socket handler = listener.Accept()) { // Start listening for connections. while (true) { // Program is suspended while waiting for an incoming connection. data = null; // An incoming connection needs to be processed. int bytesRec = -1; while (bytesRec == -1) { bytesRec = handler.Receive(bytes); data += Encoding.ASCII.GetString(bytes, 0, bytesRec); await Task.Delay(1); } byte[] msg = Encoding.ASCII.GetBytes(data); using (UdpClient client = new UdpClient(KEL103Persistance.Configuration.CommandPort)) { KEL103Tools.ConfigureClient(load_address, client); client.Send(bytes, bytesRec); if (data.Contains('?')) { var rx = (await client.ReceiveAsync()).Buffer; handler.Send(rx); } } } } } } catch (Exception e) { Console.WriteLine(e.ToString()); } Console.Clear(); } }
/// <summary> /// Start inbound UDP packet handling. /// </summary> /// <param name="recvBufferSize">The size of the receive buffer for /// the UDP socket. This value is passed up to the operating system /// and used in the system networking stack. Use zero to leave this /// value as the default</param> /// <param name="asyncPacketHandling">Set this to true to start /// receiving more packets while current packet handler callbacks are /// still running. Setting this to false will complete each packet /// callback before the next packet is processed</param> /// <remarks>This method will attempt to set the SIO_UDP_CONNRESET flag /// on the socket to get newer versions of Windows to behave in a sane /// manner (not throwing an exception when the remote side resets the /// connection). This call is ignored on Mono where the flag is not /// necessary</remarks> public virtual void StartInbound(int recvBufferSize) { if (!IsRunningInbound) { m_log.DebugFormat("[UDPBASE]: Starting inbound UDP loop"); const int SIO_UDP_CONNRESET = -1744830452; IPEndPoint ipep = new IPEndPoint(m_localBindAddress, m_udpPort); m_udpSocket = new Socket( AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); try { if (m_udpSocket.Ttl < 128) { m_udpSocket.Ttl = 128; } } catch (SocketException) { m_log.Debug("[UDPBASE]: Failed to increase default TTL"); } try { // This udp socket flag is not supported under mono, // so we'll catch the exception and continue m_udpSocket.IOControl(SIO_UDP_CONNRESET, new byte[] { 0 }, null); m_log.Debug("[UDPBASE]: SIO_UDP_CONNRESET flag set"); } catch (SocketException) { m_log.Debug("[UDPBASE]: SIO_UDP_CONNRESET flag not supported on this platform, ignoring"); } // On at least Mono 3.2.8, multiple UDP sockets can bind to the same port by default. At the moment // we never want two regions to listen on the same port as they cannot demultiplex each other's messages, // leading to a confusing bug. // By default, Windows does not allow two sockets to bind to the same port. // // Unfortunately, this also causes a crashed sim to leave the socket in a state // where it appears to be in use but is really just hung from the old process // crashing rather than closing it. While this protects agains misconfiguration, // allowing crashed sims to be started up again right away, rather than having to // wait 2 minutes for the socket to clear is more valuable. Commented 12/13/2016 // m_udpSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, false); if (recvBufferSize != 0) { m_udpSocket.ReceiveBufferSize = recvBufferSize; } m_udpSocket.Bind(ipep); if (m_udpPort == 0) { m_udpPort = ((IPEndPoint)m_udpSocket.LocalEndPoint).Port; } IsRunningInbound = true; // kick off an async receive. The Start() method will return, the // actual receives will occur asynchronously and will be caught in // AsyncEndRecieve(). AsyncBeginReceive(); } }
internal LightingController(string host, int port = 8899) { endPoint = new IPEndPoint(IPAddress.Parse(host), port); }
/// <summary> /// Starts listening to the broadcast and plays back audio received from it. /// Subsequent calls to this method require to call <see cref="Stop"/> in between. /// </summary> public virtual void Start() { this.startLock.WaitOne(); this.cancellationTokenSource = new CancellationTokenSource(); Task.Factory.StartNew(() => { var currentRate = 129; var currentWidth = 16; var currentChannels = 2; var currentChannelsMapLsb = 0x03; // stereo var currentChannelsMapMsb = 0x00; var currentChannelsMap = (currentChannelsMapMsb << 8) | currentChannelsMapLsb; var localEp = new IPEndPoint(IPAddress.Any, this.multicastPort); this.udpClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); this.udpClient.Client.Bind(localEp); this.udpClient.JoinMulticastGroup(this.multicastAddress); var rsws = new BufferedWaveProvider(new WaveFormat(44100, currentWidth, currentChannels)) { BufferDuration = TimeSpan.FromMilliseconds(200), DiscardOnBufferOverflow = true }; this.output = new WaveOut() { DesiredLatency = 200 }; this.Volume = 100; this.output.Init(rsws); this.output.Play(); Task.Factory.StartNew(() => { while (!this.cancellationTokenSource.IsCancellationRequested) { try { Byte[] data = this.udpClient.Receive(ref localEp); if (data[0] != currentRate || data[1] != currentWidth || data[2] != currentChannels || data[3] != currentChannelsMapLsb || data[4] != currentChannelsMapMsb) { currentRate = data[0]; currentWidth = data[1]; currentChannels = data[2]; currentChannelsMapLsb = data[3]; currentChannelsMapMsb = data[4]; currentChannelsMap = (currentChannelsMapMsb << 8) | currentChannelsMapLsb; // TODO find a way to set a channel map in NAudio. I was not able to find any. // In practice if both the source and the receiver windows machine have the same speakers configuration setted this doesn't matter, // but in all other cases the channels will be possibly mismatched. this.output.Stop(); var rate = ((currentRate >= 128) ? 44100 : 48000) * (currentRate % 128); rsws = new BufferedWaveProvider(new WaveFormat(rate, currentWidth, currentChannels)) { BufferDuration = TimeSpan.FromMilliseconds(200), DiscardOnBufferOverflow = true }; this.output = new WaveOut() { DesiredLatency = 200 }; this.Volume = 100; this.output.Init(rsws); this.output.Play(); } rsws.AddSamples(data, 5, data.Length - 5); } catch (SocketException) { } // Usually when interrupted } }, this.cancellationTokenSource.Token); this.shutdownLock.WaitOne(); this.output.Stop(); this.udpClient.Close(); }, this.cancellationTokenSource.Token); }