2018-07-24 15:53:34 -04:00
#!/usr/bin/env python3
2018-01-25 16:14:16 -08:00
#
# SPDX-License-Identifier: GPL-2.0
#
import sys , os , os . path , getopt
import socket , time
import subprocess
import select
def read ( sock , n ) :
2018-07-24 15:53:34 -04:00
buf = b ' '
2018-01-25 16:14:16 -08:00
while len ( buf ) < n :
rem = n - len ( buf )
try : s = sock . recv ( rem )
2018-07-24 15:53:34 -04:00
except ( socket . error ) as e : return b ' '
2018-01-25 16:14:16 -08:00
buf + = s
return buf
def send ( sock , s ) :
total = len ( s )
count = 0
while count < total :
try : n = sock . send ( s )
2018-07-24 15:53:34 -04:00
except ( socket . error ) as e : n = 0
2018-01-25 16:14:16 -08:00
if n == 0 :
return count ;
count + = n
return count
SERVER_PORT = 12877
MAX_PORTS = 2
serverPort = SERVER_PORT
serverSocket = None
# create passive socket
serverSocket = socket . socket ( socket . AF_INET6 , socket . SOCK_STREAM )
2019-02-04 10:43:19 -08:00
try : serverSocket . bind ( ( ' localhost ' , 0 ) )
2018-01-25 16:14:16 -08:00
except socket . error as msg :
2018-07-24 15:53:34 -04:00
print ( ' bind fails: ' + str ( msg ) )
2018-01-25 16:14:16 -08:00
sn = serverSocket . getsockname ( )
serverPort = sn [ 1 ]
cmdStr = ( " ./tcp_client.py %d & " ) % ( serverPort )
os . system ( cmdStr )
2018-07-24 15:53:34 -04:00
buf = b ' '
2018-01-25 16:14:16 -08:00
n = 0
while n < 500 :
2018-07-24 15:53:34 -04:00
buf + = b ' . '
2018-01-25 16:14:16 -08:00
n + = 1
serverSocket . listen ( MAX_PORTS )
readList = [ serverSocket ]
while True :
readyRead , readyWrite , inError = \
select . select ( readList , [ ] , [ ] , 2 )
if len ( readyRead ) > 0 :
waitCount = 0
for sock in readyRead :
if sock == serverSocket :
( clientSocket , address ) = serverSocket . accept ( )
address = str ( address [ 0 ] )
readList . append ( clientSocket )
else :
sock . settimeout ( 1 ) ;
s = read ( sock , 1000 )
n = send ( sock , buf )
sock . close ( )
serverSocket . close ( )
sys . exit ( 0 )
else :
2018-07-24 15:53:34 -04:00
print ( ' Select timeout! ' )
2018-01-25 16:14:16 -08:00
sys . exit ( 1 )