-
Notifications
You must be signed in to change notification settings - Fork 1
/
Connection.dart
56 lines (46 loc) · 1.6 KB
/
Connection.dart
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
#library('dartmud:connection');
#import('dart:io');
/**
* Connection class is a wrapper around the client socket connection
* this wrapper provides some convenience functions and automatically.
* Connection is part of the base server and not dependant on the
* mudlib itself.
*/
class Connection {
Socket _sock;
StringInputStream _strInput;
/**
* Constructs a new Connection initialized with a base socket.
* (Created by on a new connection to ServerSocket.
* Creates an internal StringInputStream from the received socket
* and assigns a default onError handler for the socket.
*/
Connection(this._sock) {
_strInput = new StringInputStream(_sock.inputStream);
_sock.onError = (Exception e) {
print("An error has occurred with Connection#$_sock:");
print(e);
_sock.close();
};
}
/**
* Reassigns the onLine function for Socket to [func].
* Used when we need to modify default command processing behaviour,
* such as when using internal line editor.
*/
set onLine(Function func) => _strInput.onLine = func;
/** Write [str] to remote client. Useful for prompting user. */
int write(String str) {
List<int> strCodes = str.charCodes();
_sock.writeList(strCodes, 0, strCodes.length);
}
/** Write [str] to remote client. Terminates with a newline character */
int writeLine(String str) => write("$str\n");
/** Returns input line from remote client */
String readLine() => _strInput.readLine().trim();
/** Notifies and closes remote client's connection */
void close() {
writeLine('Goodbye!');
_sock.close();
}
}