コード例 #1
0
ファイル: LocalSocket.go プロジェクト: hotei/simple
// how to tell server to close listener without blocking or polling?  TODO
func server_A(ready chan int, quit chan int) {
	ch := []byte{0}
	var n int
	var listener net.UnixAddr
	listener.Name = "server_socket"

	_, err := os.Open(listener.Name)
	if err == nil {
		fmt.Printf("socket already in use\n")
		os.Exit(-1)
	}
	l, err := net.ListenUnix("unix", &listener)
	if err != nil {
		fmt.Printf("ListenUnix()  failed with err: %v\n", err)
		os.Exit(1)
	}
	defer l.Close()
	t := time.Now()
	t = t.Add(10 * time.Second)
	err = l.SetDeadline(t)
	fmt.Printf("server() listener started ok, ready to accept connections\n")
	ready <- 1 // send ready signal back to main()
	for {
		//select {  didn't solve problem
		//case _ = <- quit: break
		//default:
		//}
		c, err := l.AcceptUnix()
		if err != nil {
			fmt.Printf("server() accept socket failed with err: %v\n", err)
			break
		}
		fmt.Printf("server() accepted connection from client\n")
		n, err = c.Read(ch)
		if err != nil || n != 1 {
			fmt.Printf("server() read socket failed with err: %v\n", err)
			os.Exit(1)
		}
		ch[0] *= 10 // modify input data and send it back
		n, err = c.Write(ch)
		if err != nil || n != 1 {
			fmt.Printf("server() write to socket failed with err: %v\n", err)
			os.Exit(1)
		}
		fmt.Printf("server() wrote byte value = %d to socket\n", ch)
		c.Close()
	}
	fmt.Printf("Cleaning up after listener\n")
	err = os.Remove(listener.Name)
	if err != nil {
		log.Panicf("cant remove socket")
	}
	quit <- 1
}