Advertisement
Guest User

Untitled

a guest
Aug 11th, 2020
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 0.97 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4.     "bufio"
  5.     "fmt"
  6.     "net"
  7. )
  8.  
  9. func handleConnection(c net.Conn) {
  10.  
  11.     localChan := make(chan string)
  12.  
  13.     // starts a goroutine to handle incoming message from client
  14.     go func() {
  15.         for {
  16.             netData, err := bufio.NewReader(c).ReadString('\n')
  17.             if err != nil {
  18.                 fmt.Println(err)
  19.                 return
  20.             }
  21.             if netData[:8] == "message:" {
  22.                 res := "back at you: " + netData[8:]
  23.                 localChan <- res
  24.             } else if netData[:4] == "brc:" {
  25.                 //res := "broadcast: " + netData[4:]
  26.                 // what to do?
  27.             }
  28.         }
  29.     }()
  30.  
  31.     // do something when received channel
  32.     for {
  33.         select {
  34.         case loc := <-localChan:
  35.             c.Write([]byte(loc))
  36.         }
  37.     }
  38. }
  39.  
  40. func main() {
  41.  
  42.     l, err := net.Listen("tcp", "127.0.0.1:305")
  43.     if err != nil {
  44.         fmt.Println(err)
  45.         return
  46.     }
  47.     defer l.Close()
  48.  
  49.     for {
  50.         con, err := l.Accept()
  51.         if err != nil {
  52.             fmt.Println(err)
  53.             return
  54.         }
  55.  
  56.         // create separate goroutine for each new client
  57.         go handleConnection(con)
  58.     }
  59. }
  60.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement