這是我以前寫的一個socket小應用,其中也順便用到了一點點多線程的東西。
這個socket用戶端是我為了方便公司的儲值系統調試而寫的一個小應用。由它跟儲值系統進行socket通訊,自動完成儲值的測試工作。
看代碼吧:
import socket,threaddef Communicate(s): phoneno = raw_input("Please input your PhoneNo.:(Push Enter to use default)") #Get local phoneno if (len(phoneno)) == 0: phoneno= '123456' phoneno="phone:"+phoneno #Add a prefix of phoneno s.send(phoneno) #Send data string to server print '>> %s'%phoneno data = s.recv(4096) #Get response data from server print '<< %s'%data #0819022324 process_string='*571253*0861235468*1*2617*3#' s.send(process_string) print '>> %s'%process_string print '<< %s'%s.recv(4096) s.send('6506') print '>> %s'%'6506' print '<< %s'%s.recv(4096) s.close() #Disconnect the socket connection print 'End!' #End the program def Refill(): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #Create a socket try: #s.connect((socket.gethostname(), 8888)) #Connect to target server s.connect(('192.168.4.129', 8888)) #Connect to target server except: print "Connect to '%s' failed!"%(socket.gethostname()) else: #Communicate(s) thread.start_new_thread(Communicate,(s,)) #Socket communicate on a new thread. print "-----------------------------------------------------------"print "Welcom to use Python Socket Tools.SocketTest.py\nThis program is designed to test FRS4 socket communicate test\n----Powered by Lucker."if(__name__=='__main__'): Refill()
《完》