Anonymous user
Chat server: Difference between revisions
Undo revision 187383 by Wswiss (talk) Does not ocompile
(→{{header|Go}}: added synchronization to clients, added logging using package log) |
|||
Line 536:
import (
"
"bytes"▼
"fmt"
"net"
"
"
▲ "bytes"
)
// Quick and dirty error handling.
// A type for storing the connections.▼
func error_(err error, r int) {
type clientMap struct {▼
fmt.Printf("Error: %v\n", err)
if r >= 0 {
os.Exit(r)
}▼
}
▲// A type for storing the connections.
// A method that makes clientMap compatible with io.Writer, allowing it to be
// used with fmt.Fprintf().
func (cm clientMap) Write(buf []byte) (n int, err error) {
▲ for _, c := range cm.cl {
// Write to each client in a seperate goroutine.
go c.Write(buf)
}
n = len(buf)
return
}
// Check if a name exists; if it doesn't, add it.
func (cm clientMap)
for k := range cm {
if name == k {
return false▼
}
▲ return false
}
cm[name] = c
return true▼
▲}
▲ return true
}
Line 589 ⟶ 587:
func init() {
// Initialize the map.
clients =
}
Line 599 ⟶ 596:
br := bufio.NewReader(c)
fmt.Fprintf(c, "Please enter your name: ")
buf, err := br.ReadBytes('\n')
if err != nil {
return
}
Line 610 ⟶ 606:
if name == "" {
fmt.
}
// Try to add the connection to the map.
if !clients.
fmt.Fprintf(c, "!!! %
return
}
// Send a message telling the clients who connected.
fmt.Fprintf(clients, "+++ %
// Send a disconnected message when the function returns.
defer fmt.Fprintf(clients, "--- %
// Remove the client from the list.
defer
for {
Line 649 ⟶ 644:
// Send the message to all the clients.
fmt.Fprintf(clients, "%
}
}
// Flags. Use -help for usage info.▼
var (▼
port = flag.Int("port", 23, "Port to listen on")▼
help = flag.Bool("help", false, "Display this")▼
)▼
func main() {
▲ // Flags. Use -help for usage info.
▲ var (
port int
help bool
▲ )
flag.Parse()
if
flag.Usage()
return
Line 668 ⟶ 664:
// Initialize a new listener.
lis, err := net.Listen("tcp", fmt.Sprintf(":%
if err != nil {
}
Line 677 ⟶ 673:
c, err := lis.Accept()
if err != nil {
continue
}
|