示例#1
0
文件: socket.go 项目: jworrell/GoMU
func HandleClientSocket(eng *engine.Engine, conn net.Conn) {
	reader := bufio.NewReader(conn)
	writer := make(chan *message.Message, WRITE_QUEUE)
	kill := make(chan bool)

	associatedObj := object.NewObject(nil, object.DUMMY_ID)
	associatedObj.SetWriter(writer)

	defer func() {
		conn.Close()
		associatedObj.SetWriter(nil)
		kill <- true
	}()

	go func() {
		socketWriter := bufio.NewWriter(conn)

		for {
			select {
			case writerMsg := <-writer:
				_, err := socketWriter.WriteString(writerMsg.Data + "\n")

				if err != nil {
					log.Println("Unexpected error (write socket): ", err)
				}

				err = socketWriter.Flush()

				if err != nil {
					log.Println("Unexpected error (flush socket): ", err)
				}

			case <-kill:
				return
			}

		}
	}()

	for {
		rawMessage, err := reader.ReadString('\n')
		if err != nil {
			return
		}

		trimmedMessage := strings.TrimSpace(rawMessage)
		splitMessage := strings.SplitN(trimmedMessage, " ", 2)
		msg := message.MakeMutableMessage(splitMessage[0])

		if len(splitMessage) > 1 {
			msg.Append(splitMessage[1])
		}

		msg.Finalize()

		eng.Do(&associatedObj, msg)
	}
}
示例#2
0
文件: database.go 项目: jworrell/GoMU
func (db *Database) CreateObject() *object.Object {
	db.Lock()
	defer db.Unlock()

	id := db.getNextId()
	obj := object.NewObject(db.saver, id)

	return obj
}
示例#3
0
文件: database.go 项目: jworrell/GoMU
func (db *Database) getOrCreateObj(saver chan *object.SerializableObject, id object.ObjectID) *object.Object {
	db.Lock()
	defer db.Unlock()

	obj := db.objects[id]

	if obj == nil {
		obj = object.NewObject(saver, id)
		db.objects[id] = obj
	}

	return obj
}
示例#4
0
func WSConnection(eng *engine.Engine, ws *websocket.Conn) {
	decoder := json.NewDecoder(ws)
	writer := make(chan *message.Message, WRITE_QUEUE)
	kill := make(chan bool)

	associatedObj := object.NewObject(nil, object.DUMMY_ID)
	associatedObj.SetWriter(writer)

	defer func(o *object.Object) {
		associatedObj.SetWriter(nil)
		kill <- true
	}(associatedObj)

	go func() {
		encoder := json.NewEncoder(ws)

		for {
			select {
			case writerMsg := <-writer:
				err := encoder.Encode(writerMsg)
				if err != nil {
					log.Println("Unexpected error (encode JSON): ", err)
				}

			case <-kill:
				return
			}

		}
	}()

	for {
		readerMsg := &message.Message{}
		err := decoder.Decode(readerMsg)
		if err != nil {
			if err != io.EOF {
				log.Println("Unexpected error (decode JSON): ", err)
			}
			return
		}

		readerMsg.Finalize()
		eng.Do(&associatedObj, readerMsg)
	}
}