聊天室包括以下功能:
- 聊天
- 超时检查断开连接
- 查看用户列表
- 改名
- 退出
server.go
package main
import (
"fmt"
"net"
"strings"
"time"
)
func main() {
port := "8888"
listener, err := net.Listen("tcp", ":"+port)
if err != nil {
fmt.Println(err)
return
}
fmt.Printf("聊天室开启成功!正在监听%s端口!\n", port)
connMap := make(map[net.Conn]string)
for {
conn, err := listener.Accept()
if err != nil {
fmt.Println(err)
continue
}
connMap[conn] = conn.RemoteAddr().String()
notifyAllNewUserLogin(connMap[conn], connMap)
go HandlerConn(conn, connMap)
}
}
func HandlerConn(conn net.Conn, connMap map[net.Conn]string) {
buf := make([]byte, 1024)
defer handlerConnClose(conn, connMap, 1)
keepAlive := make(chan bool)
go func(conn net.Conn) {
for {
select {
case <-keepAlive:
case <-time.After(1 * time.Minute):
handlerConnClose(conn, connMap, 2)
return
}
}
}(conn)
help(conn)
for {
n, err := conn.Read(buf)
if err != nil {
return
}
keepAlive <- true
msg := strings.Trim(string(buf[:n]), "\r\n")
handleMsg(conn, connMap, msg)
}
}
func handlerConnClose(conn net.Conn, connMap map[net.Conn]string, t int) {
userExit(conn, connMap, t)
_ = conn.Close()
}
func notifyAllNewUserLogin(name string, connMap map[net.Conn]string) {
for curConn := range connMap {
msg := time.Now().Format(" 15:04:05 ") + " === [" + name + "] " + "login! === \n"
_, err := curConn.Write([]byte(msg))
if err != nil {
fmt.Printf("提醒[%s]新用户上线失败\n", connMap[curConn])
continue
}
}
}
func notifyAllNewUserLogout(name string, connMap map[net.Conn]string, t int) {
for curConn := range connMap {
msg := ""
if t == 1 {
msg = time.Now().Format(" 15:04:05 ") + " === [" + name + "] " + "logout! === \n"
} else if t == 2 {
msg = time.Now().Format(" 15:04:05 ") + " === [" + name + "] " + "timeout! === \n"
}
_, err := curConn.Write([]byte(msg))
if err != nil {
fmt.Printf("提醒[%s]新用户下线失败\n", connMap[curConn])
continue
}
}
}
func handleMsg(conn net.Conn, connMap map[net.Conn]string, msg string) {
parseArr := strings.Split(msg, "|")
if len(parseArr) > 1 && parseArr[0] == "func" {
switch parseArr[1] {
case "rename":
{
if len(parseArr) == 3 {
rename(conn, connMap, parseArr[2])
} else {
syntaxError(conn)
}
}
case "list":
{
if len(parseArr) == 2 {
list(conn, connMap)
} else {
syntaxError(conn)
}
}
case "exit":
{
if len(parseArr) == 2 {
userExit(conn, connMap, 1)
} else {
syntaxError(conn)
}
}
}
} else {
broadcast(conn, connMap, msg)
}
}
func broadcast(conn net.Conn, connMap map[net.Conn]string, msg string) {
for curConn := range connMap {
_, err := curConn.Write([]byte(time.Now().Format(" 15:04:05 ") + connMap[conn] + " : " + msg + "\n"))
if err != nil {
fmt.Printf("向[%s]发送广播失败\n", connMap[curConn])
return
}
}
}
func userExit(conn net.Conn, connMap map[net.Conn]string, t int) {
name, exist := connMap[conn]
if exist {
delete(connMap, conn)
notifyAllNewUserLogout(name, connMap, t)
}
}
func syntaxError(conn net.Conn) {
_, err := conn.Write([]byte("syntaxError!\n"))
if err != nil {
fmt.Printf("向[%s]发送<语法错误>失败\n", conn)
return
}
}
func rename(conn net.Conn, connMap map[net.Conn]string, newName string) {
_, err := conn.Write([]byte("success!\n"))
if err != nil {
fmt.Printf("向[%s]发送<修改名称成功>失败\n", conn)
return
}
connMap[conn] = newName
}
func list(conn net.Conn, connMap map[net.Conn]string) {
msg := "=====================\n"
msg += "User List:\n"
for curConn, name := range connMap {
msg += name
if conn == curConn {
msg += " (me) "
}
msg += "\n"
}
msg += "=====================\n"
_, err := conn.Write([]byte(msg))
if err != nil {
fmt.Printf("向[%s]发送<当前用户列表>失败\n", conn)
return
}
}
func help(conn net.Conn) {
msg :=
`
==================================================================================================
Introduction:
This is a easy chat room!
You can chat with other people by this client!
As you input anything, other people in the room can see it, also, you can see their input!
If you do nothing within 3 minutes, the client will go offline!
Command List:
<anything> - chat with others
func|help - get some help
func|rename|<Your New Name> - change your name
func|list - to see who is online
func|exit - go offline
by Aurora~
=================================================================================================
`
_, err := conn.Write([]byte(msg))
if err != nil {
fmt.Printf("向[%s]发送<语法错误>失败\n", conn)
return
}
}
client.go
package main
import (
"fmt"
"net"
"strings"
)
func main() {
host := "localhost"
port := "8888"
conn, err := net.Dial("tcp", host+":"+port)
if err != nil {
fmt.Println(err)
return
}
fmt.Println("已连接到", conn.RemoteAddr())
go func() {
buf := make([]byte, 5*1024)
for {
n, err := conn.Read(buf)
if err != nil {
return
}
msg := string(buf[:n])
fmt.Print(msg)
}
}()
for {
var msg string
_, _ = fmt.Scanf("%s", &msg)
msg = strings.Trim(msg, "\r\n")
if "exit" == msg {
fmt.Printf("close connect...\n")
return
}
_, _ = conn.Write([]byte(msg))
}
}
|