2024-11-23 03:30:23 +00:00
|
|
|
package hodu
|
2024-11-12 13:59:37 +00:00
|
|
|
|
|
|
|
import "fmt"
|
|
|
|
import "net"
|
2024-11-16 15:47:15 +00:00
|
|
|
import "sync"
|
2024-11-12 13:59:37 +00:00
|
|
|
|
2024-11-19 15:35:58 +00:00
|
|
|
func NewClientPeerConn(r *ClientRoute, c *net.TCPConn, id uint32) (*ClientPeerConn) {
|
2024-11-12 13:59:37 +00:00
|
|
|
var cpc ClientPeerConn
|
|
|
|
|
|
|
|
cpc.route = r
|
|
|
|
cpc.conn = c
|
|
|
|
cpc.conn_id = id
|
|
|
|
cpc.stop_req.Store(false)
|
2024-11-19 15:31:14 +00:00
|
|
|
cpc.server_peer_eof.Store(false)
|
2024-11-12 13:59:37 +00:00
|
|
|
|
|
|
|
return &cpc
|
|
|
|
}
|
|
|
|
|
2024-11-16 15:47:15 +00:00
|
|
|
func (cpc *ClientPeerConn) RunTask(wg *sync.WaitGroup) error {
|
2024-11-12 13:59:37 +00:00
|
|
|
//var conn *net.TCPConn
|
|
|
|
//var addr *net.TCPAddr
|
|
|
|
var err error
|
|
|
|
var buf [4096]byte
|
|
|
|
var n int
|
|
|
|
|
2024-11-16 15:47:15 +00:00
|
|
|
defer wg.Done()
|
2024-11-12 13:59:37 +00:00
|
|
|
|
|
|
|
fmt.Printf("CONNECTION ESTABLISHED TO PEER... ABOUT TO READ DATA...\n")
|
|
|
|
for {
|
|
|
|
n, err = cpc.conn.Read(buf[:])
|
|
|
|
if err != nil {
|
|
|
|
fmt.Printf("unable to read from the client-side peer %s - %s\n", cpc.addr, err.Error())
|
|
|
|
break
|
|
|
|
}
|
|
|
|
|
|
|
|
// TODO: guarded call..
|
|
|
|
err = cpc.route.cts.psc.Send(MakePeerDataPacket(cpc.route.id, cpc.conn_id, buf[0:n]))
|
|
|
|
if err != nil {
|
|
|
|
fmt.Printf("unable to write data to server - %s\n", err.Error())
|
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-11-17 05:57:56 +00:00
|
|
|
cpc.route.cts.psc.Send(MakePeerStoppedPacket(cpc.route.id, cpc.conn_id)) // nothing much to do upon failure. no error check here
|
|
|
|
|
2024-11-12 13:59:37 +00:00
|
|
|
cpc.ReqStop()
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (cpc *ClientPeerConn) ReqStop() {
|
|
|
|
// TODO: because of connect delay in Start, cpc.p may not be yet ready. handle this case...
|
|
|
|
if cpc.stop_req.CompareAndSwap(false, true) {
|
|
|
|
if cpc.conn != nil {
|
|
|
|
cpc.conn.Close()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2024-11-19 15:31:14 +00:00
|
|
|
|
|
|
|
func (cpc* ClientPeerConn) CloseWrite() {
|
|
|
|
if cpc.server_peer_eof.CompareAndSwap(false, true) {
|
|
|
|
if cpc.conn != nil {
|
2024-11-19 15:35:58 +00:00
|
|
|
cpc.conn.CloseWrite()
|
2024-11-19 15:31:14 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|