Skip to content

Commit

Permalink
send msg to peer
Browse files Browse the repository at this point in the history
  • Loading branch information
TATAUFO committed Jan 28, 2020
1 parent d8c626b commit 847b680
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 2 deletions.
6 changes: 4 additions & 2 deletions node/node.go
Original file line number Diff line number Diff line change
Expand Up @@ -268,8 +268,10 @@ func (n *Node) runTimeProof(sig <-chan struct{}, wait chan<- struct{}) {
}

func (n Node) broadcastMsg(msg *core.Message) error {
for pid, peer := range n.peers {
log.Info("peer id", common.Hash2String(pid), "url", peer.Url())
for _, peer := range n.peers {
if err := peer.SendMsg(msg); err != nil {
return err
}
}
return nil
}
Expand Down
32 changes: 32 additions & 0 deletions peer/peer.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,17 @@
package peer

import (
"encoding/json"
"errors"
"fmt"
"github.com/pdupub/go-pdu/core"
"golang.org/x/net/websocket"
)

var (
errPeerNotReachable = errors.New("this peer not reachable right now")
)

// Peer contain the info of websocket connection
type Peer struct {
IP string `json:"ip"`
Expand Down Expand Up @@ -57,6 +64,31 @@ func (p Peer) Url() string {
return fmt.Sprintf("ws://%s:%d/%s", p.IP, p.Port, p.NodeKey)
}

// Connected return true if this peer is connected right now
func (p *Peer) Connected() bool {
if p.conn != nil {
return true
}
return false
}

// SendMsg is used to send msg to this peer
func (p *Peer) SendMsg(msg *core.Message) error {
if !p.Connected() {
return errPeerNotReachable
}

msgBytes, err := json.Marshal(msg)
if err != nil {
return err
}
_, err = p.conn.Write(msgBytes)
if err != nil {
return err
}
return nil
}

// origin used when peer dial
func (p Peer) origin() string {
return fmt.Sprintf("http://%s:%d/", p.IP, p.Port)
Expand Down

0 comments on commit 847b680

Please sign in to comment.