File: chat.st

package info (click to toggle)
cloc 2.06-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 8,064 kB
  • sloc: perl: 30,146; cpp: 1,219; python: 623; ansic: 334; asm: 267; makefile: 244; sh: 186; sql: 144; java: 136; ruby: 111; cs: 104; pascal: 52; lisp: 50; haskell: 35; f90: 35; cobol: 35; objc: 25; php: 22; javascript: 15; fortran: 9; ml: 8; xml: 7; tcl: 2
file content (82 lines) | stat: -rw-r--r-- 1,850 bytes parent folder | download | duplicates (5)
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
"SimpleChat -- a SimpleTCP handler for a chat server"
"http://sblinn.jottit.com/gnu_smalltalk_simplechat_tcp_server"

Namespace current addSubspace: #SimpleChat!
Namespace current: SimpleChat!

Object subclass: #Handler
  instanceVariableNames: 'clients'
  classVariableNames: ''
  poolDictionaries: ''
  category: ''!

!Handler class methodsFor: 'instance creation'!

new
  | chatHandler |
  chatHandler := super new.
  chatHandler init.
  ^chatHandler
!!

!Handler methodsFor: 'initialization'!

init
  clients := Dictionary new.
  ^self
!!

!Handler methodsFor: 'handling'!

handle: aSocket
  [self handleSocket: aSocket] fork
!!

!Handler methodsFor: 'internal handling'!

handleSocket: aSocket
  | Name |
  'Name: ' displayOn: aSocket.
  aSocket flush.
  Name := (aSocket nextLine).
  (clients includesKey: Name) ifTrue: [
    'Sorry, that name is in use.' displayOn: aSocket.
    (Character nl asString) displayOn: aSocket.
    self handle: aSocket
  ] ifFalse: [
    self handleMessage: ('New user: ', Name) from: '[System]'.
    clients at: Name put: aSocket.
    self handleClient: aSocket named: Name
  ]
!

handleClient: aSocket named: Name
  [
    | Message |
    self sendPrompt: aSocket.
    Message := (aSocket nextLine).
    self handleMessage: Message from: Name.
  ] repeat
!

handleMessage: Message from: Name
  clients associationsDo: [ :assoc |
    (Name = (assoc key)) ifFalse: [
      self sendMessage: ((Character nl asString), Name, ' sent: ', Message) to: (assoc value).
      self sendPrompt: (assoc value)
    ] ifTrue: [
      self sendMessage: ('You sent: ', Message) to: (assoc value)
    ]]
!

sendMessage: Message to: aSocket
  Message displayOn: aSocket.
  (Character nl asString) displayOn: aSocket
!

sendPrompt: aSocket
    '> ' displayOn: aSocket.
    aSocket flush
!!

Namespace current: SimpleChat superspace!