plugeth/server.go

122 lines
2.3 KiB
Go
Raw Normal View History

package main
import (
"container/list"
2014-01-09 22:15:51 +00:00
"net"
"log"
_"time"
"github.com/ethereum/ethdb-go"
"github.com/ethereum/ethutil-go"
)
type Server struct {
// Channel for shutting down the server
shutdownChan chan bool
// DB interface
db *ethdb.LDBDatabase
2014-01-08 22:43:20 +00:00
// Block manager for processing new blocks and managing the block chain
blockManager *BlockManager
// Peers (NYI)
peers *list.List
}
func NewServer() (*Server, error) {
db, err := ethdb.NewLDBDatabase()
if err != nil {
return nil, err
}
ethutil.SetConfig(db)
2014-01-08 22:43:20 +00:00
server := &Server{
shutdownChan: make(chan bool),
2014-01-08 22:43:20 +00:00
blockManager: NewBlockManager(),
db: db,
peers: list.New(),
}
return server, nil
}
2014-01-09 22:15:51 +00:00
func (s *Server) AddPeer(conn net.Conn) {
peer := NewPeer(conn, s)
s.peers.PushBack(peer)
peer.Start()
log.Println("Peer connected ::", conn.RemoteAddr())
}
func (s *Server) ConnectToPeer(addr string) error {
conn, err := net.Dial("tcp", addr)
if err != nil {
return err
}
peer := NewPeer(conn, s)
s.peers.PushBack(peer)
peer.Start()
log.Println("Connected to peer ::", conn.RemoteAddr())
return nil
}
func (s *Server) Broadcast(msgType string, data []byte) {
for e := s.peers.Front(); e != nil; e = e.Next() {
if peer, ok := e.Value.(*Peer); ok {
peer.QueueMessage(msgType, data)
}
}
2014-01-09 22:15:51 +00:00
}
// Start the server
func (s *Server) Start() {
// For now this function just blocks the main thread
2014-01-09 22:15:51 +00:00
ln, err := net.Listen("tcp", ":12345")
if err != nil {
log.Fatal(err)
}
2014-01-08 22:43:20 +00:00
go func() {
for {
2014-01-09 22:15:51 +00:00
conn, err := ln.Accept()
if err != nil {
log.Println(err)
continue
}
go s.AddPeer(conn)
2014-01-08 22:43:20 +00:00
}
}()
// TMP
//go func() {
// for {
// s.Broadcast("block", Encode("blockdata"))
//
// time.Sleep(100 * time.Millisecond)
// }
// }()
}
func (s *Server) Stop() {
// Close the database
defer s.db.Close()
// Loop thru the peers and close them (if we had them)
for e := s.peers.Front(); e != nil; e = e.Next() {
if peer, ok := e.Value.(*Peer); ok {
peer.Stop()
}
}
s.shutdownChan <- true
}
// This function will wait for a shutdown and resumes main thread execution
func (s *Server) WaitForShutdown() {
<- s.shutdownChan
}