title: "An existing connection was forcibly closed by the remote host" in UDP Server on receiving
body: <p>So after a struggle with threads, I succeeded to establish a stream between a client and a server. My client is a Java Android Studio Application and the server is a C# Console.</p>
  
  <p>I want to be able to start the stream and stop it on button click from the client side. Then restart it anytime, stop, restart, stop.. etc.</p>
  
  <p>I am good to go with start, however sometimes after the first Stop, or sometimes on the first restart, or sometimes on the second restart,, It pops <code>An existing connection was forcibly closed by the remote host</code> </p>
  
  <p>on the <code>PacketReceived = serverSocket.Receive(ref client);</code></p>
  
  <p>I have no idea why and I am trying hard to debug it with no productivity. What is wrong with my logic or maybe syntax?</p>
  
  <p>C# Server Code:</p>
  
  <pre><code>class UdpServer
  {
      static void Main(string[] args)
      {
          // variables declaration block
          byte[] PacketReceived = new byte[1024];
          var MyToken = new CancellationTokenSource(); //create token for the thread cancel
          UdpClient serverSocket = new UdpClient(15000);
          string PacketMessage = "";
  
          int i = 0;
          while (true) // this while for keeping the server "listening"
          {
              Console.WriteLine("Waiting for a UDP client...");                                   // display stuff
              IPEndPoint client = new IPEndPoint(IPAddress.Any, 0);                               // prepare
              PacketReceived = serverSocket.Receive(ref client);                                  // receive packet
              PacketMessage = Encoding.ASCII.GetString(PacketReceived, 0, PacketReceived.Length); // get string from packet
              Console.WriteLine("Response from " + client.Address);                               // display stuff
              Console.WriteLine("Message " + i++ + ": " + PacketMessage + "\n");                  // display received string
  
              if (PacketMessage == "Start")
              {
                  MyToken = new CancellationTokenSource(); // for the restart, need a new token
                  Task.Run(() =&gt; Start(ref serverSocket, ref client), MyToken.Token); //start method on another thread
              }
  
              if (PacketMessage == "Stop")
              {
                  MyToken.Cancel();
              }
          }
      }
  
      static public void Start(ref UdpClient serverSocket, ref IPEndPoint client)
      {
          int i = 0;
          byte[] dataToSend;
          while (true)
          {
              try
              {
                  dataToSend = Encoding.ASCII.GetBytes(i.ToString());
                  serverSocket.Send(dataToSend, dataToSend.Length, client);
                  i++;
              }
              catch (Exception e)
              { }
          }
      }
  }
  </code></pre>
  
  <p>Java Client Code:</p>
  
  <pre><code>public class MainActivity extends AppCompatActivity {
  
      String message;
  
      @Override
      protected void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.activity_main);
  
          Button StrtBtn = (Button) findViewById(R.id.StartButton);
          Button StpBtn = (Button) findViewById(R.id.StopButton);
  
          // Start Button Click
          StrtBtn.setOnClickListener(
                  new Button.OnClickListener() {
                      public void onClick(View v) {
                          message = "Start";
                          SendUdpMsg();
                      }
                  }
          );
  
          // Stop Button Click
          StpBtn.setOnClickListener(
                  new Button.OnClickListener() {
                      public void onClick(View v) {
                          message = "Stop";
  
                      }
                  }
          );
      }
  
      public void SendUdpMsg()
      {
          Thread networkThread = new Thread() {
  
              // No local Host 127.0.0.1 in Android
              String host = "192.168.200.3"; // Server's IP
              int port = 15000;
              DatagramSocket dsocket = null;
  
              public void run() {
                  try {
                      // Get the Internet address of the specified host
                      InetAddress address = InetAddress.getByName(host);
  
                      // wrap a packet
                      DatagramPacket packetToSend = new DatagramPacket(
                              message.getBytes(),
                              message.length(),
                              address, port);
  
                      // Create a datagram socket, send the packet through it.
                      dsocket = new DatagramSocket();
                      dsocket.send(packetToSend);
  
                      // Here, I am receiving the response
                      byte[] buffer = new byte[65535]; // prepare
                      DatagramPacket packetReceived = new DatagramPacket(buffer, buffer.length); // prepare
  
                      while (true)
                      {
                          if(message == "Start")
                          {
                              dsocket.receive(packetReceived); // receive packet
                              byte[] buff = packetReceived.getData(); // convert packet to byte[]
                              final String Response = new String(buffer, 0, packetReceived.getLength());
  
                              runOnUiThread(new Runnable()
                              {
                                  @Override
                                  public void run()
                                  {
                                      // this is executed on the main (UI) thread
                                      final TextView TextOne = (TextView)findViewById(R.id.StatusText);
                                      TextOne.setText(Response);
                                  }
                              });
                          }
                          else
                          {
                              // wrap a packet to send the Stop
                              packetToSend = new DatagramPacket(
                                      message.getBytes(),
                                      message.length(),
                                      address, port);
  
                              // Create a datagram socket, send the packet through it.
                              dsocket = new DatagramSocket();
                              dsocket.send(packetToSend);
                              break; // break the whole thread
                          }
                      }
  
                  } catch (Exception e) {
                      e.printStackTrace();
                  }
              }
          };
          networkThread.start();
      }
  }
  </code></pre>