// TODO: convert this to Junit internal static void TestRequest(XDR request, XDR request2) { try { DatagramSocket clientSocket = new DatagramSocket(); IPAddress IPAddress = Sharpen.Extensions.GetAddressByName("localhost"); byte[] sendData = request.GetBytes(); byte[] receiveData = new byte[65535]; DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.Length, IPAddress , Nfs3Constant.SunRpcbind); clientSocket.Send(sendPacket); DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.Length ); clientSocket.Receive(receivePacket); clientSocket.Close(); } catch (UnknownHostException) { System.Console.Error.WriteLine("Don't know about host: localhost."); System.Environment.Exit(1); } catch (IOException) { System.Console.Error.WriteLine("Couldn't get I/O for " + "the connection to: localhost." ); System.Environment.Exit(1); } }
public override void Run() { while (running) { try { byte[] receiveData = new byte[RECEIVE_BUFFER_LENGTH]; DatagramPacket incomingPacket = new DatagramPacket(receiveData, receiveData.Length); socket.Receive(incomingPacket); System.Threading.Thread thread = new System.Threading.Thread(new ThreadStart(() => { if (receiveData[0] == RtpMidiCommand.MIDI_COMMAND_HEADER1) { midiCommandHandler.handle(receiveData, new model.RtpMidiServer(incomingPacket.Address, incomingPacket.Port)); } else { midiMessageHandler.Handle(receiveData, new RtpMidiServer(incomingPacket.Address.HostName, incomingPacket.Port)); } })); thread.Start(); } catch (SocketTimeoutException ignored) { } catch (IOException e) { Log.Error("RtpMidi", "IOException while receiving", e); } } socket.Close(); }
// Nothing to do. public virtual void Destroy() { if (registrationSocket != null && !registrationSocket.IsClosed()) { registrationSocket.Close(); } }
public void Close() { _sendRunning = false; _listenRunning = false; #if UNITY_EDITOR udpClient.Close(); #endif }
/// <summary>method to close the datagram socket</summary> public override void Close() { base.Close(); if (datagramSocket != null) { datagramSocket.Close(); } }
public static bool disconnect() { if (connected) { socket.Close(); connected = false; } return(true); }
internal override void StopInternal() { if (client != null) { #if __WINDOWS__ client.Dispose(); client = null; #else client.Close(); #endif } session = null; }
/// <summary> /// Called when the script is destroyed (see https://docs.unity3d.com/Manual/ExecutionOrder.html) /// </summary> private void OnDestroy() { #if NETFX_CORE //await Task.Run(_impl.CancelIOAsync()); _impl.Dispose(); #else stopThread = true; _impl.Close(); if (socketThread != null) { socketThread.Abort(); // aborts thread } #endif }
public override void Close() { if (udp != null) { #if XRUWP && !UNITY_EDITOR await udp.CancelIOAsync(); udp.Dispose(); #else receive.Abort(); udp.Close(); #endif udp = null; base.Close(); } }
private void DataListener() { IPEndPoint localEndpoint = new IPEndPoint(IPAddress.Any, 0); udpClient = new UdpClient(localEndpoint); udpClient.Client.ReceiveBufferSize = 65507 * 32; udpClient.Client.SendBufferSize = 65507 * 32; IPAddress listenIP = ((IPEndPoint)udpClient.Client.LocalEndPoint).Address; int listenPort = ((IPEndPoint)udpClient.Client.LocalEndPoint).Port; _listening = true; Debug.Log("Client listening on " + listenIP.ToString() + ":" + listenPort); while (_running) { try { byte[] buffer = udpClient.Receive(ref localEndpoint);//this is the evil bastard that crashes on an ICMP message String data = Encoding.ASCII.GetString(buffer); MSG msg = new MSG(data); lock (_receiveQueueLock) { _receiveQueue.Enqueue(msg); } } catch (SocketException e) { //OK, since this was a bitch to figure out, here is some documentation for what is going on, and why we encounter exceptions when receiving data //Context: The way our multi-client-udp-middleware works: packets are sent from Client A from any available (random) port to the predefined port of Client B. //Client B then looks at the packet's originating (random) port that A used to send the packet and adds Client A to the list of clients to broadcast outgoing packets to. //When sending packets back from B to A, it will now use the (random) port as its destination. //As a consequence, here in Unity we must send and receive data with the same UdpClient using the same port. //However, on some windows machines sending data to a port where there is no listener results in an ICMP response WSAECONNRESET //E.g. see here: https://stackoverflow.com/questions/7201862/an-existing-connection-was-forcibly-closed-by-the-remote-host //(This situation can occur if Unity is started before e.g. ASAP is running; in that case there is nobody listening to our packets) //This ICMP response then silently kind of half-closes our UdpClient connection.... //Weirdly enough we can still continue sending data, but when we try to call UdpClient.Receive() it throws an exception --- EVEN IF THERE IS DATA WAITING IN THE BUFFER AT THAT VERY MOMENT. //Even weirdly-er, we can just ignore the exception and continue using the udpClient for sending and receiving...! //The current workaround simply catches the exception and ignores it :) //Unfortunately, the incoming packet that caused the exception is lost } } udpClient.Close(); }
// destroy the connection public static void Close() { if (!StubMode) { #if WINDOWS_APP || WINDOWS_PHONE_APP udpSocket.Dispose(); udpSocket = null; udpWriter = null; #else udpSocket.Close(); udpSocket = null; #endif } Stop(); }
public void OnApplicationQuit() { _running = false; _listening = false; send_MRSTE.Set(); send_MRSTE.Reset(); _sendTask.Join(500); _listenTask.Join(500); _heartbeatTask.Join(500); try { _sendTask.Abort(); } catch (Exception) { Debug.Log("_sendTask.Abort failed"); //throw; } try { _listenTask.Abort(); } catch (Exception) { Debug.Log("_listenTask.Abort failed"); //throw; } try { _heartbeatTask.Abort(); } catch (Exception) { Debug.Log("_heartbeatTask.Abort failed"); //throw; } try { udpClient.Close(); } catch (Exception) { Debug.Log("udpClient.Close failed"); //throw; } Debug.Log("exit of UDPMultiClientMiddleware"); #if !UNITY_EDITOR && UNITY_METRO #else //_sendTask.Join(500); //_listenTask.Join(500); //_heartbeatTask.Join(500); #endif }
/// <summary>Udp /// ①ブロードキャスト受信用ソケットの生成,ブロードキャスト受信待ち状態を作る /// </summary> public async Task createReceiveUdpSocket() { waiting = true; string address = null; try { //waiting = trueの間、ブロードキャストを受け取る while (waiting) { //受信用ソケット DatagramSocket receiveUdpSocket = new DatagramSocket(udpPort); byte[] buf = new byte[256]; DatagramPacket packet = new DatagramPacket(buf, buf.Length); //await Task.Run( //ゲスト端末からのブロードキャストを受け取る //受け取るまでは待ち状態になる await Task.Run(() => receiveUdpSocket.Receive(packet)); //受信バイト数取得 //int length = packet.getLength(); int length = packet.Length; //受け取ったパケットを文字列にする //address = new String(buf, 0, length); address = System.Text.Encoding.UTF8.GetString(buf); //↓③で使用 returnIpAdress(address); receiveUdpSocket.Close(); //); } } catch (SocketException e) { e.PrintStackTrace(); } catch (IOException e) { e.PrintStackTrace(); } }
private void DataListener() { IPEndPoint anyIP = new IPEndPoint(IPAddress.Any, 0); if (!_useMatchmakingServer) { anyIP = new IPEndPoint(IPAddress.Any, _listenPort); } udpClient = new UdpClient(anyIP); udpClient.Client.ReceiveBufferSize = 65507 * 32; udpClient.Client.SendBufferSize = 65507 * 32; //_udpClient.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer, a big value like 0x40000) _listenPort = ((IPEndPoint)udpClient.Client.LocalEndPoint).Port; if (debugLevel > 0) { Debug.Log("Client listening on " + _listenPort); } _listenRunning = true; IPEndPoint recvEP = new IPEndPoint(IPAddress.Any, 0); while (_listenRunning) { try { byte[] receivedPackage = udpClient.Receive(ref recvEP); HandleReceivedData(receivedPackage); } catch (Exception e) { if (_listenRunning) { Debug.LogWarning("Exception in UDPConnector.DataListener: " + e); } } } udpClient.Close(); if (debugLevel > 0) { Debug.Log("DataListener Stopped"); } }
/// <summary>Udp /// 同一Wi-fiに接続している全端末に対してブロードキャスト送信を行う /// </summary> void sendBroadcast() { string myIpAddress = getIpAddress(); int count = 0; //送信回数を10回に制限する while (count < 10) { try { DatagramSocket udpSocket = new DatagramSocket(udpPort); udpSocket.Broadcast = true; //public DatagramPacket(byte[] buf, int length, InetAddress address, int port); byte[] IpAddressdata = System.Text.Encoding.UTF8.GetBytes(myIpAddress); DatagramPacket packet = new DatagramPacket(IpAddressdata /*myIpAddress.getBytes()*/, myIpAddress.Length, getBroadcastAddress(), udpPort); udpSocket.Send(packet); udpSocket.Close(); } catch (SocketException e) { e.PrintStackTrace(); } catch (IOException e) { e.PrintStackTrace(); } //5秒待って再送信を行う try { Thread.Sleep(5000); count++; } catch (InterruptedIOException e) { e.PrintStackTrace(); } } }
/// <exception cref="System.IO.IOException"/> /// <exception cref="System.Exception"/> public virtual void TestRegistration() { XDR req = new XDR(); RpcCall.GetInstance(++xid, RpcProgramPortmap.Program, RpcProgramPortmap.Version, RpcProgramPortmap.PmapprocSet, new CredentialsNone(), new VerifierNone()).Write( req); PortmapMapping sent = new PortmapMapping(90000, 1, PortmapMapping.TransportTcp, 1234 ); sent.Serialize(req); byte[] reqBuf = req.GetBytes(); DatagramSocket s = new DatagramSocket(); DatagramPacket p = new DatagramPacket(reqBuf, reqBuf.Length, pm.GetUdpServerLoAddress ()); try { s.Send(p); } finally { s.Close(); } // Give the server a chance to process the request Thread.Sleep(100); bool found = false; IDictionary <string, PortmapMapping> map = (IDictionary <string, PortmapMapping>)Whitebox .GetInternalState(pm.GetHandler(), "map"); foreach (PortmapMapping m in map.Values) { if (m.GetPort() == sent.GetPort() && PortmapMapping.Key(m).Equals(PortmapMapping. Key(sent))) { found = true; break; } } Assert.True("Registration failed", found); }
private void DataListener() { IPEndPoint localEndpoint = new IPEndPoint(IPAddress.Any, 0); udpClient = new UdpClient(localEndpoint); udpClient.Client.ReceiveBufferSize = 65507; udpClient.Client.SendBufferSize = 65507; int listenPort = ((IPEndPoint)udpClient.Client.LocalEndPoint).Port; _listening = true; Debug.Log("Client listening on " + listenPort); while (_running) { byte[] buffer = udpClient.Receive(ref localEndpoint); lock (_receiveQueueLock) { _receiveQueue.Enqueue(Encoding.ASCII.GetString(buffer)); } } udpClient.Close(); }
public void Run() { while (running) { try { byte[] receiveData = new byte[RECEIVE_BUFFER_LENGTH]; DatagramPacket incomingPacket = InitDatagramPacket(receiveData); socket.Receive(incomingPacket); handler.handle(receiveData, new model.RtpMidiServer(incomingPacket.Address, incomingPacket.Port)); } catch (SocketTimeoutException ignored) { } catch (IOException e) { Log.Error("RtpMidi", "IOException while receiving", e); } } socket.Close(); }
/// <exception cref="System.IO.IOException"/> public virtual void Run() { IPAddress IPAddress = Extensions.GetAddressByName(host); byte[] sendData = request.GetBytes(); byte[] receiveData = new byte[65535]; // Use the provided socket if there is one, else just make a new one. DatagramSocket socket = this.clientSocket == null ? new DatagramSocket() : this.clientSocket; try { DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.Length, IPAddress , port); socket.Send(sendPacket); socket.SetSoTimeout(500); DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.Length ); socket.Receive(receivePacket); // Check reply status XDR xdr = new XDR(Arrays.CopyOfRange(receiveData, 0, receivePacket.GetLength())); RpcReply reply = RpcReply.Read(xdr); if (reply.GetState() != RpcReply.ReplyState.MsgAccepted) { throw new IOException("Request failed: " + reply.GetState()); } } finally { // If the client socket was passed in to this UDP client, it's on the // caller of this UDP client to close that socket. if (this.clientSocket == null) { socket.Close(); } } }
/// <summary>Checks to see if a specific port is available.</summary> /// <remarks> /// Checks to see if a specific port is available. /// <br /> /// Source: Apache's mina project, via stack overflow /// http://stackoverflow.com/questions/434718/ /// sockets-discover-port-availability-using-java /// </remarks> /// <param name="port">the port to check for availability</param> public static bool Available(int port) { ServerSocket ss = null; DatagramSocket ds = null; try { ss = new ServerSocket(port); ss.SetReuseAddress(true); ds = new DatagramSocket(port); ds.SetReuseAddress(true); return(true); } catch (IOException) { } finally { if (ds != null) { ds.Close(); } if (ss != null) { try { ss.Close(); } catch (IOException) { } } } // should not be thrown return(false); }
void ShutDownClient() { _udpClient.Close(); _udpClient = null; }
public void StopListen() { shouldRestartSocketListen = false; socket.Close(); }