Chat server: Difference between revisions

Content added Content deleted
(add javascript (node.js) solution)
(→‎{{header|Go}}: language changes: error type and delete function)
Line 163: Line 163:
<lang go>package main
<lang go>package main


import(
import (
"os"
"os"
"fmt"
"fmt"
Line 173: Line 173:


// Quick and dirty error handling.
// Quick and dirty error handling.
func error(err os.Error, r int) {
func error_(err error, r int) {
fmt.Printf("Error: %v\n", err)
fmt.Printf("Error: %v\n", err)


Line 186: Line 186:
// A method that makes clientMap compatible with io.Writer, allowing it to be
// A method that makes clientMap compatible with io.Writer, allowing it to be
// used with fmt.Fprintf().
// used with fmt.Fprintf().
func (cm clientMap)Write(buf []byte) (n int, err os.Error) {
func (cm clientMap) Write(buf []byte) (n int, err error) {
for _, c := range(cm) {
for _, c := range cm {
// Write to each client in a seperate goroutine.
// Write to each client in a seperate goroutine.
go c.Write(buf)
go c.Write(buf)
Line 198: Line 198:


// Check if a name exists; if it doesn't, add it.
// Check if a name exists; if it doesn't, add it.
func (cm clientMap)Add(name string, c net.Conn) (bool) {
func (cm clientMap) Add(name string, c net.Conn) bool {
for k := range(cm) {
for k := range cm {
if name == k {
if name == k {
return false
return false
Line 228: Line 228:
buf, err := br.ReadBytes('\n')
buf, err := br.ReadBytes('\n')
if err != nil {
if err != nil {
error(err, -1)
error_(err, -1)
return
return
}
}
Line 251: Line 251:
defer func() {
defer func() {
// Remove the client from the list.
// Remove the client from the list.
clients[name] = nil, false
delete(clients, name)
}()
}()


Line 267: Line 267:


switch {
switch {
// Support for '/me' type messages.
// Support for '/me' type messages.
case string(buf[0:3]) == "/me":
case string(buf[0:3]) == "/me":
buf = append([]byte(name), buf[3:]...)
buf = append([]byte(name), buf[3:]...)
default:
default:
// Prepend the user-name and '> '.
// Prepend the user-name and '> '.
buf = append([]byte(name + "> "), buf...)
buf = append([]byte(name+"> "), buf...)
}
}


Line 282: Line 282:
func main() {
func main() {
// Flags. Use -help for usage info.
// Flags. Use -help for usage info.
var(
var (
port int
port int
help bool
help bool
Line 298: Line 298:
lis, err := net.Listen("tcp", fmt.Sprintf(":%v", port))
lis, err := net.Listen("tcp", fmt.Sprintf(":%v", port))
if err != nil {
if err != nil {
error(err, 1)
error_(err, 1)
}
}


Line 305: Line 305:
c, err := lis.Accept()
c, err := lis.Accept()
if err != nil {
if err != nil {
error(err, -1)
error_(err, -1)
continue
continue
}
}