AirControl  1.3.0
Open Source, Modular, and Extensible Flight Simulator For Deep Learning Research
NetworkCommunicator.cs
1 using System;
2 using System.Collections;
3 using System.Collections.Generic;
4 using System.Net;
5 using Newtonsoft.Json.Linq;
6 using System.Net.Sockets;
7 using System.Text;
8 using System.Threading;
9 using UnityEngine;
10 using Newtonsoft.Json;
11 using AirControl;
12 using Communicator;
13 using Commons;
14 
15 
16 namespace Communicator
17 {
21  public class NetworkCommunicator : MonoBehaviour
22  {
23 
24  #region public members
25  #endregion
26 
27  #region private members
28  private TcpListener tcpListener;
36  private Thread tcpListenerThread;
40  private TcpClient connectedTcpClient;
41  // provide base input to access variables
42  [Header("Airplane Input Required")]
43  [Tooltip("Drag and drop here the AC_BaseAirplane_Input.cs OR AC_XboxAirplane_Input.cs")]
44  public AC_BaseAirplane_Input currentReadings;
45 
46  public InputHandle inputHandle;
47  public OutputHandle outputHandle;
48  bool isOutput;
49  string outputmsg;
50  #endregion
51 
52  #region Default Methods
53  // Use this for initialization
54  void Start () {
55  // Start TcpServer background thread
56  tcpListenerThread = new Thread (new ThreadStart(ListenForIncommingRequests));
57  tcpListenerThread.IsBackground = true;
58  tcpListenerThread.Start();
59  }
60  #endregion
61 
62  #region Custom Methods
63  public void ListenForIncommingRequests () {
67  try {
68  // Create listener on localhost port 8052.
69  tcpListener = new TcpListener(IPAddress.Parse("0.0.0.0"), CommonFunctions.ServerPort);
70 
71  tcpListener.Start();
72  Debug.Log("Started Server At Port "+CommonFunctions.ServerPort);
73  Byte[] bytes = new Byte[1024];
74  if(inputHandle)
75  {
76  while (true) {
77  using (connectedTcpClient = tcpListener.AcceptTcpClient()) {
78  // Get a stream object for reading
79 
80  using (NetworkStream stream = connectedTcpClient.GetStream()) {
81  int length;
82  // Read incomming stream into byte arrary.
83  while ((length = stream.Read(bytes, 0, bytes.Length)) != 0)
84  {
85  try
86  {
87  var incommingData = new byte[length];
88  Array.Copy(bytes, 0, incommingData, 0, length);
89  // Convert byte array to string message.
90  string clientMessage = Encoding.ASCII.GetString(incommingData);
91  clientMessage = clientMessage.Replace("}{", "} | {");
92  string [] inputArray = clientMessage.Split('|');
93  foreach(string eachInput in inputArray)
94  {
95  isOutput = false;
96  try{
97  var inputJson = JObject.Parse(eachInput);
98  inputHandle.ParseInput(inputJson);
99  isOutput = bool.Parse(inputJson["IsOutput"].ToString());
100  }
101  catch (SocketException e){
102  Debug.LogError($"JsonReaderException : { e.Source}");
103  isOutput = true;
104  }
105  catch (JsonReaderException e){
106  Debug.LogError($"JsonReaderException : { e.Source}");
107  isOutput = true;
108  }
109  // once received the message, send message in return
110  if(isOutput){
111 
112  outputHandle.ParseOutput(ref outputmsg);
113  SendMessage(ref outputmsg);
114  }
115  else{
116  string logOutput = outputHandle.LogOutput();
117  SendMessage(ref logOutput);
118  }
119  }
120  }
121  catch(Exception ex)
122  {
123  Debug.LogWarning("Socket exception: " + ex.ToString());
124  isOutput = true;
125  }
126  ResetThings();
127  }
128  }
129  }
130  }
131  }
132  else
133  {
134  Debug.Log("InputHandle is detached in from Network manager. Go to Unity Hierarchy, look at inspector, drag and drop InputHandle onto Network communicator");
135  }
136  }
137  catch (SocketException ex) {
138  Debug.LogWarning("Socket exception: " + ex.ToString());
139  // tcpListener.Stop();
140  isOutput = true;
141  }
142  }
143  // /// <summary>
144  // /// Reset things after the response is sent
145  // /// </summary>
146  public void ResetThings()
147  {
148  if(StaticOutputSchema.IfCollision)
149  {
150  StaticOutputSchema.IfCollision = false;
151 
152  }
153 
154  }
155 
159  public void SendMessage(ref String outStructSerialized) {
160  if (connectedTcpClient == null) {
161  return;
162  }
163  try {
164  NetworkStream stream = connectedTcpClient.GetStream();
165  if (stream.CanWrite) {
166  // string serverMessage = "This is a message from your server.";
167  // Convert string message to byte array.
168  byte[] serverMessageAsByteArray = Encoding.ASCII.GetBytes(outStructSerialized);
169  // Write byte array to socketConnection stream.
170  stream.Write(serverMessageAsByteArray, 0, serverMessageAsByteArray.Length);
171  }
172  }
173  catch (SocketException socketException) {
174  Debug.LogWarning("Socket exception: " + socketException);
175  }
176  }
177  #endregion
178 
179  }
180 
181 }
Communicator.OutputHandle.ParseOutput
void ParseOutput(ref string outputmsg)
Prepare output object and return json string to be dispatched
Definition: OutputHandle.cs:24
Communicator.OutputHandle
Handle outbound request from the TCP socket
Definition: OutputHandle.cs:15
AirControl.AC_BaseAirplane_Input
Base class to listen for keyboard Inputs
Definition: AC_BaseAirplane_Input.cs:12
Communicator.NetworkCommunicator.ListenForIncommingRequests
void ListenForIncommingRequests()
Runs in background TcpServerThread; Handles incomming TcpClient requests
Definition: NetworkCommunicator.cs:66
Communicator.NetworkCommunicator
Class to manage the TCP network function
Definition: NetworkCommunicator.cs:21
Communicator.InputHandle.ParseInput
void ParseInput(JObject inputJson)
Parse input coming from network
Definition: InputHandle.cs:26
Communicator.NetworkCommunicator.SendMessage
void SendMessage(ref String outStructSerialized)
Send message to client using socket connection.
Definition: NetworkCommunicator.cs:159
Communicator.OutputHandle.LogOutput
string LogOutput()
Just Log output if the entire output is not required
Definition: OutputHandle.cs:94
AirControl
Definition: AirplaneSelector.cs:8
Communicator.InputHandle
Handle inbound request from the TCP socket
Definition: InputHandle.cs:15
Communicator
Definition: InputHandle.cs:10
Commons
Definition: AirplaneProperties.cs:14