Chat server: Difference between revisions

1,793 bytes added ,  13 years ago
Added Go example.
({{omit from|PARI/GP}})
(Added Go example.)
Line 157:
Response -> Response
end.
</lang>
 
=={{header|Go}}==
 
<lang go>package main
 
import(
"os"
"fmt"
"net"
"flag"
"bufio"
"bytes"
)
 
func error(err os.Error, r int) {
fmt.Printf("Error: %v\n", err)
 
if r >= 0 {
os.Exit(r)
}
}
 
type clientMap map[string]net.Conn
 
func (cm clientMap)Write(buf []byte) (n int, err os.Error) {
for _, c := range(cm) {
go c.Write(buf)
}
 
n = len(buf)
 
return
}
 
func (cm clientMap)Add(name string, c net.Conn) (bool) {
for k := range(cm) {
if name == k {
return false
}
}
 
cm[name] = c
 
return true
}
 
var clients clientMap
 
func init() {
clients = make(clientMap)
}
 
func client(c net.Conn) {
defer c.Close()
 
br := bufio.NewReader(c)
 
fmt.Fprintf(c, "Please enter your name: ")
 
buf, err := br.ReadBytes('\n')
if err != nil {
error(err, -1)
return
}
name := string(bytes.Trim(buf, " \t\n\r\x00"))
 
if name == "" {
fmt.Fprintf(c, "!!! %v is invalid !!!\n", name)
}
 
if !clients.Add(name, c) {
fmt.Fprintf(c, "!!! %v is not available !!!\n", name)
return
}
 
fmt.Fprintf(clients, "+++ %v connected +++\n", name)
 
for {
buf, err = br.ReadBytes('\n')
if err != nil {
break
}
buf = bytes.Trim(buf, " \t\n\r\x00")
 
if len(buf) == 0 {
continue
}
 
switch {
case string(buf[0:3]) == "/me":
buf = append([]byte(name), buf[3:]...)
default:
buf = append([]byte(name + "> "), buf...)
}
 
fmt.Fprintf(clients, "%v\n", string(buf))
}
 
fmt.Fprintf(clients, "--- %v disconnected ---\n", name)
 
clients[name] = nil, false
}
 
func main() {
var port int
flag.IntVar(&port, "port", 23, "Port to listen on")
flag.Parse()
 
lis, err := net.Listen("tcp", fmt.Sprintf(":%v", port))
if err != nil {
error(err, 1)
}
 
for {
c, err := lis.Accept()
if err != nil {
error(err, -1)
continue
}
 
go client(c)
}
}
</lang>