Sockets are used nearly everywhere.This is a bit of socket code form python.This program is designed to test FRS4 socket communicate test as below.
import socket
print "-----------------------------------------------------------"
print "Welcom to use Python Socket Tools./nThis program is designed to test FRS4 socket communicate test/n----Powered by Lucker."
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #Create a socket
try:
s.connect((socket.gethostname(), 8888)) #Connect to target server
except:
print "Connect to '%s' failed!"%(socket.gethostname())
else:
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
process_string='*571253*61235468*1*2617*5#'
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
Meybe,we need a special class for our communication in the socket program.We call it "MySocket" as below
class mysocket:
'''demonstration class only coded for clarity, not efficiency '''
def __init__(self, sock=None):
if sock is None:
self.sock = socket.socket( socket.AF_INET, socket.SOCK_STREAM)
else:
self.sock = sock
def connect(self, host, port):
self.sock.connect((host, port))
def mysend(self, msg):
totalsent = 0
while totalsent < MSGLEN:
sent = self.sock.send(msg[totalsent:])
if sent == 0:
raise RuntimeError,"socket connection broken"
totalsent = totalsent + sent
def myreceive(self):
msg = ''
while len(msg) < MSGLEN:
chunk = self.sock.recv(MSGLEN-len(msg))
if chunk == '':
raise RuntimeError,"socket connection broken"
msg = msg + chunk
return msg