Server.cs
2.74 KB
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
/**********************
********LAVID**********
*******VLibras*********
*------------------------------------------------------------------------
*Description:
*Server gets pts from Core (client) by TCP connection
*and runs the animations until a final tag is found.
*------------------------------------------------------------------------
*Author: Claudiomar Araujo # claudiomar.araujo@lavid.ufpb.br
*------------------------------------------------------------------------
***********************/
using UnityEngine;
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
public class Server {
TcpClient client;
NetworkStream stream;
TcpListener server;
Semaphore serverSemaphore;
PlayerManager inspector;
Int32 port = 5555;
public Server(Semaphore ss, PlayerManager inspec){
serverSemaphore = ss;
inspector = inspec;
} // constructor
public void startServer(){
try{
IPAddress localAddr = IPAddress.Parse("0.0.0.0");
server = new TcpListener (localAddr, port);
server.Start(); // Starts listening for incoming connection requests.
client = server.AcceptTcpClient(); // Accepts a pending connection request.
stream = client.GetStream();
serverSemaphore.Release(); // Releases InspectorScript.Start() [Connection]
getPTSFromCore();
}
catch(SocketException e){
Debug.Log(e);
closeConnections();
Application.Quit();
}
catch(IOException e){
Debug.Log(e);
closeConnections();
Application.Quit();
}
catch(Exception e){
Debug.Log(e);
closeConnections();
Application.Quit();
}
} // startServer
// Receives glosa and pts from Core
void getPTSFromCore()
{
try
{
Byte[] bytes = new Byte[1024];
String data = null;
int i;
Byte[] sendToCore;
Debug.Log("getPTSFromCore");
while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
{
data = System.Text.UTF8Encoding.UTF8.GetString(bytes, 0, i);
sendToCore = System.Text.UTF8Encoding.UTF8.GetBytes("OK\0"); // allows Core to send next stream
stream.Write(sendToCore, 0, sendToCore.Length);
Debug.Log(data);
if ( ! data.Equals("FINALIZE"))
inspector.playMessage(data);
}
Debug.Log("~~ getPTSFromCore");
}
catch (Exception e)
{
throw new Exception(e.Source);
}
} // getPTSFromCore
public void sendFinalizeToCore(){
Byte[] sendToCore = System.Text.UTF8Encoding.UTF8.GetBytes("FINALIZE\0"); // ativar para o core
stream.Write(sendToCore, 0, sendToCore.Length);
}
public void closeConnections(){
try {
client.Close();
stream.Close();
server.Stop();
}
catch(SocketException e){
Debug.Log(e);
closeConnections();
}
catch(IOException e){
Debug.Log(e);
closeConnections();
}
} // closeConnections
}