Golang

关注公众号 jb51net

关闭
首页 > 脚本专栏 > Golang > Go TCP实现聊天室

Go语言通过TCP协议实现聊天室功能

作者:谷隐凡二

这篇文章主要为大家详细介绍了Go语言中如何通过TCP协议实现聊天室功能,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下

1、服务端

package main
 
import (
	"fmt"
	"net"
	"sync"
)
 
type ChatServer struct {
	clients    map[string]net.Conn
	clientsMux sync.Mutex
}
 
func NewChatServer() *ChatServer {
	return &ChatServer{
		clients: make(map[string]net.Conn),
	}
}
 
func (s *ChatServer) broadcast(message string, sender string) {
	s.clientsMux.Lock()
	defer s.clientsMux.Unlock()
 
	for clientAddr, conn := range s.clients {
		if clientAddr != sender {
			fmt.Fprintf(conn, "[%s]: %s\n", sender, message)
		}
	}
}
 
func (s *ChatServer) handleConnection(conn net.Conn) {
	defer conn.Close()
 
	clientAddr := conn.RemoteAddr().String()
 
	fmt.Printf("New connection from %s\n", clientAddr)
 
	s.clientsMux.Lock()
	s.clients[clientAddr] = conn
	s.clientsMux.Unlock()
 
	for {
		buffer := make([]byte, 1024)
		n, err := conn.Read(buffer)
		if err != nil {
			fmt.Printf("Error reading from %s: %v\n", clientAddr, err)
			break
		}
 
		message := string(buffer[:n])
		fmt.Printf("[%s]: %s\n", clientAddr, message)
 
		s.broadcast(message, clientAddr)
	}
}
 
func main() {
	server := NewChatServer()
 
	listener, err := net.Listen("tcp", ":8080")
	if err != nil {
		fmt.Println("Error:", err)
		return
	}
	defer listener.Close()
 
	fmt.Println("TCP chat server listening on :8080")
 
	for {
		conn, err := listener.Accept()
		if err != nil {
			fmt.Println("Error accepting connection:", err)
			continue
		}
		go server.handleConnection(conn)
	}
}

2、客户端

package main
 
import (
	"bufio"
	"fmt"
	"net"
	"os"
)
 
func readMessages(conn net.Conn) {
	reader := bufio.NewReader(conn)
	for {
		message, err := reader.ReadString('\n')
		if err != nil {
			fmt.Println("Error reading message:", err)
			break
		}
		fmt.Print(message)
	}
}
 
func main() {
	conn, err := net.Dial("tcp", "127.0.0.1:8080")
	if err != nil {
		fmt.Println("Error connecting to server:", err)
		return
	}
	defer conn.Close()
 
	go readMessages(conn)
 
	for {
		scanner := bufio.NewScanner(os.Stdin)
		scanner.Scan()
		message := scanner.Text()
 
		_, err := conn.Write([]byte(message + "\n"))
		if err != nil {
			fmt.Println("Error sending message:", err)
			break
		}
	}
}

3、实现效果

到此这篇关于Go语言通过TCP协议实现聊天室功能的文章就介绍到这了,更多相关Go TCP实现聊天室内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文