| 1 |
"SimpleChat -- a SimpleTCP handler for a chat server" |
| 2 |
"http://sblinn.jottit.com/gnu_smalltalk_simplechat_tcp_server" |
| 3 |
|
| 4 |
Namespace current addSubspace: #SimpleChat! |
| 5 |
Namespace current: SimpleChat! |
| 6 |
|
| 7 |
Object subclass: #Handler |
| 8 |
instanceVariableNames: 'clients' |
| 9 |
classVariableNames: '' |
| 10 |
poolDictionaries: '' |
| 11 |
category: ''! |
| 12 |
|
| 13 |
!Handler class methodsFor: 'instance creation'! |
| 14 |
|
| 15 |
new |
| 16 |
| chatHandler | |
| 17 |
chatHandler := super new. |
| 18 |
chatHandler init. |
| 19 |
^chatHandler |
| 20 |
!! |
| 21 |
|
| 22 |
!Handler methodsFor: 'initialization'! |
| 23 |
|
| 24 |
init |
| 25 |
clients := Dictionary new. |
| 26 |
^self |
| 27 |
!! |
| 28 |
|
| 29 |
!Handler methodsFor: 'handling'! |
| 30 |
|
| 31 |
handle: aSocket |
| 32 |
[self handleSocket: aSocket] fork |
| 33 |
!! |
| 34 |
|
| 35 |
!Handler methodsFor: 'internal handling'! |
| 36 |
|
| 37 |
handleSocket: aSocket |
| 38 |
| Name | |
| 39 |
'Name: ' displayOn: aSocket. |
| 40 |
aSocket flush. |
| 41 |
Name := (aSocket nextLine). |
| 42 |
(clients includesKey: Name) ifTrue: [ |
| 43 |
'Sorry, that name is in use.' displayOn: aSocket. |
| 44 |
(Character nl asString) displayOn: aSocket. |
| 45 |
self handle: aSocket |
| 46 |
] ifFalse: [ |
| 47 |
self handleMessage: ('New user: ', Name) from: '[System]'. |
| 48 |
clients at: Name put: aSocket. |
| 49 |
self handleClient: aSocket named: Name |
| 50 |
] |
| 51 |
! |
| 52 |
|
| 53 |
handleClient: aSocket named: Name |
| 54 |
[ |
| 55 |
| Message | |
| 56 |
self sendPrompt: aSocket. |
| 57 |
Message := (aSocket nextLine). |
| 58 |
self handleMessage: Message from: Name. |
| 59 |
] repeat |
| 60 |
! |
| 61 |
|
| 62 |
handleMessage: Message from: Name |
| 63 |
clients associationsDo: [ :assoc | |
| 64 |
(Name = (assoc key)) ifFalse: [ |
| 65 |
self sendMessage: ((Character nl asString), Name, ' sent: ', Message) to: (assoc value). |
| 66 |
self sendPrompt: (assoc value) |
| 67 |
] ifTrue: [ |
| 68 |
self sendMessage: ('You sent: ', Message) to: (assoc value) |
| 69 |
]] |
| 70 |
! |
| 71 |
|
| 72 |
sendMessage: Message to: aSocket |
| 73 |
Message displayOn: aSocket. |
| 74 |
(Character nl asString) displayOn: aSocket |
| 75 |
! |
| 76 |
|
| 77 |
sendPrompt: aSocket |
| 78 |
'> ' displayOn: aSocket. |
| 79 |
aSocket flush |
| 80 |
!! |
| 81 |
|
| 82 |
Namespace current: SimpleChat superspace! |