2024-11-23 12:30:23 +09:00
package hodu
2024-11-12 22:59:37 +09:00
import "net"
2024-11-17 00:47:15 +09:00
import "sync"
2024-11-12 22:59:37 +09:00
2024-12-01 17:20:16 +09:00
func NewClientPeerConn ( r * ClientRoute , c * net . TCPConn , id uint32 , pts_raddr string , pts_laddr string ) * ClientPeerConn {
2024-11-12 22:59:37 +09:00
var cpc ClientPeerConn
cpc . route = r
cpc . conn = c
cpc . conn_id = id
2024-12-01 17:20:16 +09:00
cpc . pts_raddr = pts_raddr
cpc . pts_laddr = pts_laddr
cpc . pts_eof . Store ( false )
2024-11-12 22:59:37 +09:00
cpc . stop_req . Store ( false )
return & cpc
}
2024-11-17 00:47:15 +09:00
func ( cpc * ClientPeerConn ) RunTask ( wg * sync . WaitGroup ) error {
2024-11-12 22:59:37 +09:00
var err error
var buf [ 4096 ] byte
var n int
2024-11-17 00:47:15 +09:00
defer wg . Done ( )
2024-11-12 22:59:37 +09:00
for {
n , err = cpc . conn . Read ( buf [ : ] )
if err != nil {
2024-12-03 20:28:04 +09:00
cpc . route . cts . cli . log . Write ( cpc . route . cts . sid , LOG_ERROR ,
"Failed to read from the client-side peer(%d,%d,%s,%s) - %s" ,
cpc . route . id , cpc . conn_id , cpc . conn . RemoteAddr ( ) . String ( ) , cpc . conn . LocalAddr ( ) . String ( ) , err . Error ( ) )
2024-11-12 22:59:37 +09:00
break
}
err = cpc . route . cts . psc . Send ( MakePeerDataPacket ( cpc . route . id , cpc . conn_id , buf [ 0 : n ] ) )
if err != nil {
2024-12-03 20:28:04 +09:00
cpc . route . cts . cli . log . Write ( cpc . route . cts . sid , LOG_ERROR ,
"Failed to write peer(%d,%d,%s,%s) data to server - %s" ,
cpc . route . id , cpc . conn_id , cpc . conn . RemoteAddr ( ) . String ( ) , cpc . conn . LocalAddr ( ) . String ( ) , err . Error ( ) )
2024-11-12 22:59:37 +09:00
break
}
}
2024-12-03 20:28:04 +09:00
cpc . route . cts . psc . Send ( MakePeerStoppedPacket ( cpc . route . id , cpc . conn_id , cpc . conn . RemoteAddr ( ) . String ( ) , cpc . conn . LocalAddr ( ) . String ( ) ) ) // nothing much to do upon failure. no error check here
2024-11-12 22:59:37 +09:00
cpc . ReqStop ( )
2024-12-03 20:28:04 +09:00
cpc . route . RemoveClientPeerConn ( cpc )
2024-11-12 22:59:37 +09:00
return nil
}
func ( cpc * ClientPeerConn ) ReqStop ( ) {
if cpc . stop_req . CompareAndSwap ( false , true ) {
if cpc . conn != nil {
cpc . conn . Close ( )
}
}
}
2024-11-20 00:31:14 +09:00
2024-11-25 19:46:18 +09:00
func ( cpc * ClientPeerConn ) CloseWrite ( ) {
2024-12-01 17:20:16 +09:00
if cpc . pts_eof . CompareAndSwap ( false , true ) {
2024-11-20 00:31:14 +09:00
if cpc . conn != nil {
2024-11-20 00:35:58 +09:00
cpc . conn . CloseWrite ( )
2024-11-20 00:31:14 +09:00
}
}
}