Ejemplo n.º 1
0
func (self *Server) Start() error {
	self.s.Listen(self.config.Port)
	defer self.Close()

	<-self.start
	fmt.Println("server start")

	for {
		conn, err := self.s.Accept()
		if err != nil {
			fmt.Println(err)
			return err
		} else {

			genClientID := func() string {
				self.joinedNumber++
				return fmt.Sprintf("%s.%d", self.config.ServerName, self.joinedNumber)
			}

			cid := genClientID()

			fmt.Println("client id :" + cid)
			tempClient := client.CreateClient(conn, cid)
			self.d.Pending <- tempClient

			go func(c *client.Client) {
				defer func() {
					self.d.Quiting <- c
				}()

				for {
					rawData, ok := c.GetIncoming()
					if !ok {
						break
					}

					fmt.Println(rawData)

					err := self.d.MsgManager.PutMessage(
						message.NewMessage(
							self.config.Pt, string(cid), "", rawData, daemon.MESSAGE_TYPE_TOSERVICE))

					if err != nil {
						fmt.Sprintf("server.error|msg:%s", err)
						self.d.MsgManager.PutMessage(
							daemon.NewSimpleMessage(
								string(cid),
								fmt.Sprintf("server.error|msg:%s", err)))
					}
				}
			}(tempClient)
		}
	}
}
Ejemplo n.º 2
0
func startClient(ip string) {
	fmt.Println("client")
	conn, err := net.Dial("tcp", ip)
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(ip)

	client := client.CreateClient(conn, "")

	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)

	go func() {
		for {
			msg, ok := client.GetIncoming()
			if !ok {
				break
			}
			out.WriteString(msg + "\n")
			out.Flush()
		}
	}()
	// go func(c net.Conn, m chan string) {
	// 	for data := range m {
	// 		cn, err := c.Write([]byte(data))
	// 		log.Println(cn, err)
	// 	}
	// }(client.Conn, message)

	for {
		line, _, _ := in.ReadLine()
		client.PutOutgoing(string(line))
	}
}