作者:諾言DJ_791 | 来源:互联网 | 2023-12-09 08:58
用go语言实现一对一聊天服务器(服务器与客户端)
1)服务器开启,等待来自客户端的连接
2)客户端连接服务器,与服务器实现一对一聊天,输入close关闭与服务器连接
3)服务器收到close字符串,关闭当前连接,继续等待下一个客户端连接
server
// server project main.go
package main
import (
"fmt"
"net"
)
//var ConnMap map[string]*net.TCPConn
func main() {
listen_socket, err := net.Listen("tcp", "127.0.0.1:8000")
if err != nil {
fmt.Println("server start error")
}
defer listen_socket.Close()
fmt.Println("server is wating ....")
for {
conn, err := listen_socket.Accept()
if err != nil {
fmt.Println("conn fail ...")
}
fmt.Println("connect client successed")
var msg string
for {
msg = ""
data := make([]byte, 255)
msg_read, err := conn.Read(data)
if msg_read == 0 || err != nil {
break
}
msg_read_str := string(data[0:msg_read])
if msg_read_str == "close" {
conn.Write([]byte("close"))
break
}
//fmt.Println(string(data[0:msg_read]))
fmt.Println("client say: ", msg_read_str)
fmt.Printf("say to client: ")
fmt.Scan(&msg)
//conn.Write([]byte("hello clientn"))
//msg_write := []byte(msg)
conn.Write([]byte(msg))
}
fmt.Println("client Closen")
conn.Close()
}
}
client
// client project main.go
package main
import (
"fmt"
"net"
)
func main() {
conn, err := net.Dial("tcp", "127.0.0.1:8000")
if err != nil {
fmt.Println("conn fail...")
}
fmt.Println("connect server successed")
var msg string
for {
msg = ""
fmt.Printf("say to server: ")
fmt.Scan(&msg)
//fmt.Println(msg)
//msg_write := []byte(msg)
//conn.Write(msg_write)
conn.Write([]byte(msg))
//fmt.Println([]byte(msg))
data := make([]byte, 255)
msg_read, err := conn.Read(data)
if msg_read == 0 || err != nil {
break
}
msg_read_str := string(data[0:msg_read])
if msg_read_str == "close" {
conn.Write([]byte("close"))
break
}
fmt.Println("server say:", msg_read_str)
}
conn.Close()
}
程序截图:
go语言实现多人聊天 链接:https://blog.csdn.net/dyd961121/article/details/81252920