当前位置:   article > 正文

Golang 实现 websocket 通讯(一个服务器,两个客户端)

Golang 实现 websocket 通讯(一个服务器,两个客户端)

运行客户端时首先要输入自己的名字,两个客户端输入的名字不能一样。

先上运行结果:

服务器端:

客户端1:

客户端2:

话不多说,直接上代码:

服务器端:

  1. package main
  2. import (
  3. "fmt"
  4. "github.com/gorilla/websocket"
  5. "log"
  6. "net/http"
  7. )
  8. var upgrader = websocket.Upgrader{
  9. CheckOrigin: func(r *http.Request) bool {
  10. return true
  11. },
  12. }
  13. // Client represents a connected client
  14. type Client struct {
  15. conn *websocket.Conn
  16. }
  17. // Message represents a message from a client
  18. type Message struct {
  19. Sender string `json:"sender"`
  20. Recipient string `json:"recipient"`
  21. Content string `json:"content"`
  22. }
  23. var clients = make(map[*Client]bool)
  24. var broadcast = make(chan Message)
  25. func handleConnections(w http.ResponseWriter, r *http.Request) {
  26. conn, err := upgrader.Upgrade(w, r, nil)
  27. if err != nil {
  28. log.Println(err)
  29. return
  30. }
  31. defer conn.Close()
  32. client := &Client{conn: conn}
  33. clients[client] = true
  34. fmt.Println("Client connected")
  35. for {
  36. var msg Message
  37. err := conn.ReadJSON(&msg)
  38. if err != nil {
  39. log.Println(err)
  40. delete(clients, client)
  41. break
  42. }
  43. broadcast <- msg
  44. }
  45. }
  46. func handleMessages() {
  47. for {
  48. msg := <-broadcast
  49. for client := range clients {
  50. if client.conn != nil {
  51. err := client.conn.WriteJSON(msg)
  52. if err != nil {
  53. log.Println(err)
  54. client.conn.Close()
  55. delete(clients, client)
  56. }
  57. }
  58. }
  59. }
  60. }
  61. func main() {
  62. http.HandleFunc("/", handleConnections)
  63. go handleMessages()
  64. fmt.Println("WebSocket server listening on :8080")
  65. log.Fatal(http.ListenAndServe(":8080", nil))
  66. }

客户端1:

  1. package main
  2. import (
  3. "bufio"
  4. "fmt"
  5. "github.com/gorilla/websocket"
  6. "log"
  7. "os"
  8. )
  9. type Message struct {
  10. Sender string `json:"sender"`
  11. Recipient string `json:"recipient"`
  12. Content string `json:"content"`
  13. }
  14. func main() {
  15. conn, _, err := websocket.DefaultDialer.Dial("ws://localhost:8080", nil)
  16. if err != nil {
  17. log.Println("Error connecting to server:", err)
  18. return
  19. }
  20. defer conn.Close()
  21. go func() {
  22. for {
  23. var msg Message
  24. err := conn.ReadJSON(&msg)
  25. if err != nil {
  26. log.Println("Error reading message:", err)
  27. return
  28. }
  29. fmt.Printf("Received from %s: %s\n", msg.Sender, msg.Content)
  30. }
  31. }()
  32. fmt.Print("Enter your name: ")
  33. var name string
  34. fmt.Scanln(&name)
  35. scanner := bufio.NewScanner(os.Stdin)
  36. for scanner.Scan() {
  37. message := scanner.Text()
  38. msg := Message{Sender: name, Content: message}
  39. err := conn.WriteJSON(msg)
  40. if err != nil {
  41. log.Println("Error sending message:", err)
  42. return
  43. }
  44. }
  45. }

客户端2:

  1. package main
  2. import (
  3. "bufio"
  4. "fmt"
  5. "github.com/gorilla/websocket"
  6. "log"
  7. "os"
  8. )
  9. type Message struct {
  10. Sender string `json:"sender"`
  11. Recipient string `json:"recipient"`
  12. Content string `json:"content"`
  13. }
  14. func main() {
  15. conn, _, err := websocket.DefaultDialer.Dial("ws://localhost:8080", nil)
  16. if err != nil {
  17. log.Println("Error connecting to server:", err)
  18. return
  19. }
  20. defer conn.Close()
  21. go func() {
  22. for {
  23. var msg Message
  24. err := conn.ReadJSON(&msg)
  25. if err != nil {
  26. log.Println("Error reading message:", err)
  27. return
  28. }
  29. fmt.Printf("Received from %s: %s\n", msg.Sender, msg.Content)
  30. }
  31. }()
  32. fmt.Print("Enter your name: ")
  33. var name string
  34. fmt.Scanln(&name)
  35. scanner := bufio.NewScanner(os.Stdin)
  36. for scanner.Scan() {
  37. message := scanner.Text()
  38. msg := Message{Sender: name, Content: message}
  39. err := conn.WriteJSON(msg)
  40. if err != nil {
  41. log.Println("Error sending message:", err)
  42. return
  43. }
  44. }
  45. }

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号