Skip to content

Instantly share code, notes, and snippets.

@jasonkit
Created June 28, 2015 14:46
Show Gist options
  • Save jasonkit/7582674376aabf7eb73c to your computer and use it in GitHub Desktop.
Save jasonkit/7582674376aabf7eb73c to your computer and use it in GitHub Desktop.
simple go chatroom
package main
import (
"flag"
"fmt"
"io"
"net"
"sync"
"time"
)
func checkError(err error) {
if err != nil {
panic(err)
}
}
func main() {
isServer := flag.Bool("s", false, "running as server")
flag.Parse()
if *isServer {
addr, err := net.ResolveTCPAddr("tcp", ":11000")
checkError(err)
listener, err := net.ListenTCP("tcp", addr)
checkError(err)
var connPool []*net.TCPConn
mutex := &sync.Mutex{}
go func() {
for {
if conn, err := listener.AcceptTCP(); err != nil {
fmt.Printf("%v\n", err)
} else {
mutex.Lock()
connPool = append(connPool, conn)
mutex.Unlock()
fmt.Printf("New connection %v %v\n", conn.LocalAddr(), conn.RemoteAddr())
go func(conn *net.TCPConn) {
conn.Write([]byte(fmt.Sprintf("Hi From Server\n")))
buf := make([]byte, 128)
for {
if n, err := conn.Read(buf); err != nil {
if err != io.EOF {
fmt.Printf("%v\n", err)
} else {
mutex.Lock()
for k, v := range connPool {
if v == conn {
connPool = append(connPool[:k], connPool[k+1:]...)
break
}
}
mutex.Unlock()
fmt.Printf("Connection closed\n")
}
break
} else {
fmt.Printf("Received %d byte of data from %v:\n%v\n", n, conn, buf[:n])
for _, v := range connPool {
obuf := []byte(fmt.Sprintf("%v: ", conn.RemoteAddr()))
obuf = append(obuf, buf[:n]...)
v.Write(obuf)
}
}
}
}(conn)
}
}
}()
quit := make(chan bool)
<-quit
} else {
serverAddr, err := net.ResolveTCPAddr("tcp", "127.0.0.1:11000")
checkError(err)
localAddr, err := net.ResolveTCPAddr("tcp", ":0")
checkError(err)
conn, err := net.DialTCP("tcp", localAddr, serverAddr)
checkError(err)
go func(conn *net.TCPConn) {
buf := make([]byte, 128)
for {
if n, err := conn.Read(buf); err != nil {
if err != io.EOF {
fmt.Printf("%v\n", err)
} else {
fmt.Printf("Disconnected from Server\n")
}
break
} else {
fmt.Printf("Received %d byte of data from %v:\n%v\n", n, conn, buf[:n])
}
}
}(conn)
conn.Write([]byte(fmt.Sprintf("Hi!\n")))
time.Sleep(3 * time.Second)
conn.Write([]byte(fmt.Sprintf("I am a bot\n")))
time.Sleep(2 * time.Second)
conn.Write([]byte(fmt.Sprintf("Bye\n")))
time.Sleep(1 * time.Second)
conn.Close()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment