Advertisement
CaptainSpaceCat

TestRequester

Jul 26th, 2022
1,069
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.98 KB | None | 0 0
  1. using AsyncIO;
  2. using NetMQ;
  3. using NetMQ.Sockets;
  4. using UnityEngine;
  5. using System;
  6. using System.Collections.Generic;
  7. using System.Threading;
  8.  
  9. /// <summary>
  10. ///     Example of requester who only sends Hello. Very nice guy.
  11. ///     You can copy this class and modify Run() to suits your needs.
  12. ///     To use this class, you just instantiate, call Start() when you want to start and Stop() when you want to stop.
  13. /// </summary>
  14. public class TestRequester : RunAbleThread {
  15.  
  16.     public event Action<bool> OnReceiveResponse;
  17.     private Queue<string> outgoing;
  18.     private Mutex queueMut;
  19.     /// <summary>
  20.     ///     Request Hello message to server and receive message back. Do it 10 times.
  21.     ///     Stop requesting when Running=false.
  22.     /// </summary>
  23.     protected override void Run() {
  24.         queueMut = new Mutex();
  25.         ForceDotNet.Force(); // this line is needed to prevent unity freeze after one use, not sure why yet
  26.         using (RequestSocket client = new RequestSocket()) {
  27.             client.Connect("tcp://localhost:5555");
  28.  
  29.             while (Running) {
  30.                 queueMut.WaitOne();
  31.                 if (outgoing.Count > 0) {
  32.                     client.SendFrame(outgoing.Dequeue());
  33.  
  34.                     string message = null;
  35.                     bool gotMessage = false;
  36.                     while (Running && !gotMessage) {
  37.                         gotMessage = client.TryReceiveFrameString(out message); // this returns true if it's successful
  38.                     }
  39.                     OnReceiveResponse(message == "ACK");
  40.                 } else {
  41.                     //TODO make it not do busy cycles somehow
  42.                 }
  43.                 queueMut.ReleaseMutex();
  44.             }
  45.         }
  46.  
  47.         NetMQConfig.Cleanup(); // this line is needed to prevent unity freeze after one use, not sure why yet
  48.     }
  49.  
  50.  
  51.     public void AddSendCommand(string msg) {
  52.         queueMut.WaitOne();
  53.         outgoing.Enqueue(msg);
  54.         queueMut.ReleaseMutex();
  55.     }
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement