V
V
Vladimir Grabko2016-04-22 14:02:57
go
Vladimir Grabko, 2016-04-22 14:02:57

Why is it not sending data from the channel?

Hello. I want to send data from the server terminal to all connected clients. But I'm dumb

package main

import (
  "bufio"
  "io"
  "log"
  "net"
  "os"
  "strconv"
  "strings"
  "time"
)

const (
  Message       = "Pong"
  StopCharacter = "\r\n\r\n"
)

func SocketServer(port int) {
  listen, err := net.Listen("tcp4", ":"+strconv.Itoa(port))
  defer listen.Close()
  if err != nil {
    log.Fatalf("Прослушивание порта %d не удалось,\r\n\r\n %s", port, err)
    os.Exit(1)
  }
  log.Printf("Сервер слушает порт: %d", port)
  for {
    conn, err := listen.Accept()
    if err != nil {
      log.Fatalln(err)
      continue
    }
    go handler(conn)
  }
}
func handler(conn net.Conn) {
  defer conn.Close()
  var (
    buf = make([]byte, 1024)
    r   = bufio.NewReader(conn)
    w   = bufio.NewWriter(conn)
  )
ILOOP:
  for {
    n, err := r.Read(buf)
    data := string(buf[:n])
    switch err {
    case io.EOF:
      break ILOOP
    case nil:
      log.Println("Получил:", data)
      if isTransportOver(data) {
        break ILOOP
      }
    default:
      log.Fatalf("Ошибка при получении:%s", err)
      return
    }
  }
  //данные из канала
  msg := <-messages
  w.Write([]byte(msg))
  w.Flush()

}
func isTransportOver(data string) (over bool) {
  over = strings.HasSuffix(data, "\r\n\r\n")
  return
}
func main() {
  Command := make(chan string)

  SocketServer(3333)

  reader := bufio.NewReader(os.Stdin)
  fmt.Print("Enter text: ")
  text, _ := reader.ReadString('\n')
  messages <- text
}

When compiling, it writes to the console
C:\gopath\src\bot>go run main.go
panic: runtime error: invalid memory address or nil pointer dereference
[signal 0xc0000005 code=0x1 addr=0x0 pc=0x401613]

goroutine 1 [running]:
panic(0x547760, 0x10818030)
        C:/Go/src/runtime/panic.go:481 +0x326
main.Client(0x10802360, 0xc, 0xd05)
        C:/gopath/src/bot/main.go:47 +0x483
main.main()
        C:/gopath/src/bot/main.go:41 +0x37
exit status 2

Thank you all
Upd.
The error is that the SocketServer function is waiting for connections in an eternal loop, which means that the code
reader := bufio.NewReader(os.Stdin)
  fmt.Print("Enter text: ")
  text, _ := reader.ReadString('\n')
  messages <- text 
<code>
не когда не выполнится. Как мне это исправить?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Ilya, 2016-04-22
@lucifer-m

I have no idea how you create the messages channel, so I made a normal one.

package main

import (
  "bufio"
  "fmt"
  "io"
  "log"
  "net"
  "os"
  "strconv"
  "strings"
)

var messages chan string

func main() {
  messages = make(chan string, 10)
  var port int = 3333
  listen, err := net.Listen("tcp4", ":"+strconv.Itoa(port))
  defer listen.Close()
  if err != nil {
    log.Fatalf("Прослушивание порта %d не удалось,\r\n\r\n %s", port, err)
    os.Exit(1)
  }

  go func() {

    log.Printf("Сервер слушает порт: %d", port)
    reader := bufio.NewReader(os.Stdin)
    for {
      fmt.Print("Enter text: ")
      text, _ := reader.ReadString('\n')
      log.Print(text)
      messages <- text
    }

  }()
  for {
    conn, err := listen.Accept()
    if err != nil {
      log.Fatalln(err)
      continue
    }
    go handler(conn)
  }
}
func handler(conn net.Conn) {
  defer conn.Close()
  var (
    buf = make([]byte, 1024)
    r   = bufio.NewReader(conn)
    w   = bufio.NewWriter(conn)
  )
ILOOP:
  for {
    n, err := r.Read(buf)
    data := string(buf[:n])
    switch err {
    case io.EOF:
      break ILOOP
    case nil:
      log.Println("Получил:", data)
      if isTransportOver(data) {
        break ILOOP
      }
    default:
      log.Fatalf("Ошибка при получении:%s", err)
      return
    }
  }
  //данные из канала
  msg := <-messages
  w.Write([]byte(msg))
  w.Flush()

}
func isTransportOver(data string) (over bool) {
  over = strings.HasSuffix(data, "\r\n\r\n")
  return
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question