-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathServerAdapter.cs
More file actions
121 lines (114 loc) · 3.06 KB
/
Copy pathServerAdapter.cs
File metadata and controls
121 lines (114 loc) · 3.06 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
119
120
121
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
/// <summary>
/// Adapter to connect to jNetworkInterface server.
/// </summary>
public class ServerAdapter
{
private TcpClient socket;
private string hostname;
private int port;
private bool isConnected;
/// <summary>
/// Constructor that takes hostname and port.
/// </summary>
/// <param name="hostname">Hostname or IP Address</param>
/// <param name="port">Port number</param>
public ServerAdapter(string hostname, int port)
{
this.hostname = hostname;
this.port = port;
}
/// <summary>
/// Check connection.
/// </summary>
/// <returns>Connection status</returns>
public bool IsConnected()
{
connect();
return isConnected;
}
/// <summary>
/// Send a command to the server.
/// </summary>
/// <param name="command">Command</param>
/// <param name="data">Data to send as ArrayList</param>
/// <returns></returns>
public String SendCommand(string command, ArrayList data)
{
connect();
if (isConnected)
{
try
{
StreamWriter writer = new StreamWriter(socket.GetStream(), Encoding.ASCII);
// Output the command
writer.WriteLine(command);
// Add data
if (data != null && data.Count != 0)
// Push data to sockets
foreach (var itm in data)
writer.WriteLine(itm);
// Output end command sequence
writer.WriteLine("END COMMAND");
// Flush me baby
writer.Flush();
// Read it
StreamReader reader = new StreamReader(socket.GetStream(), Encoding.ASCII);
// Storage vars
string line;
string response = "";
while ((line = reader.ReadLine()) != null)
response += line;
// Clean stuff up
writer.Close();
reader.Close();
closeConnection();
return response;
}
catch
{
return "ERROR";
}
}
else
return "INVALID CONNECTION";
}
/// <summary>
/// Connect to the server.
/// </summary>
private void connect()
{
// Make the connection.
if (!isConnected)
{
try
{
socket = new TcpClient(hostname, port);
isConnected = socket.Connected;
}
catch
{
isConnected = false;
}
}
}
/// <summary>
/// Close server connection.
/// </summary>
private void closeConnection()
{
try
{
socket.Close();
isConnected = false;
}
catch { }
}
}