Exemplo n.º 1
0
 // 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 void StartListen()
        {
            // UDP服务器监听的端口
            int port = 4000;

            // 接收的字节大小,客户端发送的数据不能超过这个大小
            byte[]         message        = new byte[512];
            DatagramSocket datagramSocket = new DatagramSocket(port);

            datagramSocket.Broadcast = true;
            DatagramPacket datagramPacket = new DatagramPacket(message, message.Length);

            try
            {
                while (!IsThreadDisable)
                {
                    datagramSocket.Receive(datagramPacket);
                    string   strMsg = new Java.Lang.String(datagramPacket.GetData()).Trim();
                    string[] msg    = strMsg.Split(new string[] { "\r\n" }, StringSplitOptions.None);
                }
            }
            catch (System.Exception e)
            {
            }
        }
Exemplo n.º 3
0
        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();
        }
Exemplo n.º 4
0
        // Constantly check for new messages on given port.
        private void ReceiveData()
        {
            // Open.
            this.client = new UdpClient(this.localPort);
            IPEndPoint anyIP = new IPEndPoint(IPAddress.Any, 0);

            // Infinite loop.
            try {
                byte[] data;
                string receiveString;
                while (true)
                {
                    // Receive Bytes.
                    data = client.Receive(ref anyIP);
                    if (data.Length > 0)
                    {
                        // If buffer not empty - decode it.
                        receiveString = EncodeUtilities.DecodeData(data);
                        // If string not empty and not read yet - react to it.
                        if (!string.IsNullOrEmpty(receiveString))
                        {
                                                        #if DEBUG2
                            DebugUtilities.UniversalDebug(this.sourceName, "Total Data found: " + receiveString, ref this.debugMessages);
                                                        #endif
                            if ((this.dataMessages.Count == 0) ||
                                (this.flagForce || (this.dataMessages[this.dataMessages.Count - 1] != receiveString)))
                            {
                                this.dataMessages.Add(receiveString);
                                this.connectionHistory.Add(anyIP.Address.ToString());
                                this.flagDataRead = false;
                                if (OnReceive != null)
                                {
                                    OnReceive();
                                }
                            }
                            else
                            {
                                                                #if DEBUG2
                                DebugUtilities.UniversalDebug(this.sourceName, "Message already added.", ref this.debugMessages);
                                                                #endif
                            }
                        }
                    }
                }
            } catch (SocketException exception) {
                // SocketException.
                                #if DEBUGWARNING
                DebugUtilities.UniversalWarning(this.sourceName, "SocketException: " + exception.ToString(), ref this.debugMessages);
                                #endif
            } catch (Exception exception) {
                // Exception.
                                #if DEBUGWARNING
                DebugUtilities.UniversalWarning(this.sourceName, "Exception: " + exception.ToString(), ref this.debugMessages);
                                #endif
            } finally {
                this.Disconnect();
            }
        }
 /// <summary>
 /// 如果输出的是两条Debug 是否会有信号问题
 /// </summary>
 /// <returns></returns>
 public string[] ReadToCommand()
 {
     try
     {
         datagramSocket.Receive(datagramPacket);
         string   strMsg = new Java.Lang.String(datagramPacket.GetData()).Trim();
         string[] msg    = strMsg.Split(new string[] { "\r\n" }, StringSplitOptions.None);
         return(msg);
     }
     catch (System.Exception ex)
     {
         Log.Error("UDPERROR", ex.Message);
     }
     return(new string[0]);
 }
Exemplo n.º 6
0
        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();
        }
Exemplo n.º 7
0
    // ==================================== Code that only runs on the Unity Editor / Windows Desktop ======================================================//

#if !NETFX_CORE
    // Windows thread loop
    /// <summary>
    /// Socket Thread Loop for the socket version running on Windows
    /// </summary>
    private void SocketThreadLoop()
    {
        while (!stopThread)
        {
            try
            {
                String msg = System.Text.Encoding.UTF8.GetString(_impl.Receive(ref anyIP));
                lock (messageQueue)
                {
                    messageQueue.Enqueue(msg);
                }
            }
            catch (Exception err)
            {
                Debug.Log(NAME + err.ToString());
            }
        }
    }
Exemplo n.º 8
0
        /// <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();
            }
        }
Exemplo n.º 9
0
        private void ListenAndWaitAndThrowNotification()
        {
            byte[] recvBuf = new byte[15000];
            if (socket == null || socket.IsClosed)
            {
                socket           = new DatagramSocket(UDP_LISTEN_PORT);
                socket.Broadcast = true;
            }
            DatagramPacket packet = new DatagramPacket(recvBuf, recvBuf.Length);

            socket.Receive(packet);

            string senderIP = packet.Address.HostAddress;
            string message  = Encoding.UTF8.GetString(packet.GetData());

            string[] msg = message.Split(new string[] { "::" }, StringSplitOptions.RemoveEmptyEntries);

            this.OnMessageReceived(this, msg);
            socket.Close();
        }
Exemplo n.º 10
0
        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");
            }
        }
    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();
    }
Exemplo n.º 12
0
        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();
        }
Exemplo n.º 13
0
 /// <summary>
 /// 如果输出的是两条Debug 是否会有信号问题
 /// </summary>
 /// <returns></returns>
 public byte[] ReadToCommand()
 {
     try
     {
         datagramSocket.Receive(datagramPacket);
         Readbuffer     = datagramPacket.GetData();
         DataBeginIndex = 0;
         while (Readbuffer[DataBeginIndex] != Begin)
         {
             DataBeginIndex++;
         }
         byte[] buffer = new byte[1024];
         //buffer[0] = Begin;
         int len = 0;
         while (len < 1024)
         {
             var b = (byte)Readbuffer[DataBeginIndex];
             if (b == '\n')
             {
                 if (buffer[len - 1] == '\r')
                 {
                     len -= 1;
                 }
                 return(buffer.Take(len).ToArray());
             }
             DataBeginIndex++;
             buffer[len++] = b;
         }
         //需要进行一个数据处理
         return(buffer);
     }
     catch (System.Exception ex)
     {
         Log.Error("ReadToCommand", ex.Message);
     }
     return(new byte[0]);
 }
Exemplo n.º 14
0
        /// <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();
                }
            }
        }