-
Notifications
You must be signed in to change notification settings - Fork 0
/
ScanReciever.cs
78 lines (68 loc) · 2.12 KB
/
ScanReciever.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
using UnityEngine;
using System;
using System.Threading;
using System.Net;
using System.Net.Sockets;
using System.Runtime.Serialization.Formatters.Binary;
/// <summary>
/// Class for recieving scan data over network.
/// </summary>
public class ScanReciever : MonoBehaviour {
private Thread serverThread;
private TcpListener server;
private TcpClient client;
private NetworkStream stream;
public int port;
public ScanSerializer scanSerial;
public bool scanReady; //For access by Display manager, to created network recieved scan.
/// <summary>
/// Called when ScanReciever GameObject is initialised by Unity Engine.
///
/// Starts a thread for the server Listen method.
/// </summary>
public void Start()
{
Application.runInBackground = true;
scanReady = false;
serverThread = new Thread(new ThreadStart(Listen));
serverThread.IsBackground = true;
serverThread.Start();
}
/// <summary>
/// Server listens for a client sending a scan, recieves the scan and shuts down.
/// </summary>
private void Listen()
{
try
{
server = new TcpListener(IPAddress.Any, port);
server.Start();
Debug.Log("Listening...");
while (true)
{
this.client = server.AcceptTcpClient();
Debug.Log("Client accepted");
this.stream = client.GetStream();
BinaryFormatter bf = new BinaryFormatter();
this.scanSerial = (ScanSerializer) bf.Deserialize(stream);
Debug.Log("Scan is ready!");
scanReady = true;
}
}
catch (SocketException e)
{
Debug.Log(e);
}
}
/// <summary>
/// Called when Unity application or build program is closed.
///
/// Closes the stream, disconnects the client and stops the server.
/// </summary>
public void Close()
{
stream.Close();
client.Close();
server.Stop();
}
}