Python socket (single thread)

Source: Internet
Author: User

 clients, client code:

Client Main method, S.send (); S.sendall (); S.recv (); S.connect ()

Class Client (object):

def __init__ (self, IP, portno=xxx):
Self.ip = IP
Self. PortNo = PortNo

def connect_socket (self):
Count = 1
Status = 0
While count < 6 and Status = = 0: # try 5 times in Ip::port No on the Create socket link.
Print ("Attempt%s time (s) to open socket port"% count)
Try
Self.soct = Socket.socket (socket.af_inet, socket. SOCK_STREAM) # define socket type (TCP)
Except Socket.error, E: # Socket error exception handling, here put Exception catch, the code can continue to run. The end of the function returns a function run result flag for the main function or call function to judge.
Print ("error occur during creating socket::%s"% e)
Try
Self.soct.connect (Self.ip, self. PORTNO))
Status = 1
Print ("Socket opened success:%s::%s"% (Self.ip, self.) PORTNO))
Except Socket.error, E: # Common Socket error has destination address Errors, PortNo, firewalls and other reasons
Print ("Address or port related error detected during connect to server::%s"% e)
Count + = 1
Time.sleep (3)
If status = = 0:
Return False
Return True # returns function Run result



Server, service-side code,

Service-side Main method, S.recv ();   S.send ();   S.sendall ();    S.bind ();   S.close ()

Class Server (object):
def __init__ (self, IP, portno=xxx):
Self.ip = IP
Self. PortNo = PortNo
def run_server (self):
Self.soct = Socket.socket (socket.af_inet, socket. SOCK_STREAM) # define socket type (TCP)
Self.scot.bind (self.ip,self. PORTNO))
Self.soct.listen (1) # Number of socket listeners.
CONN,ADDR = Self.soct.accept () # accepts Scoket link request.
Print ("Socket has been established with%s::%s"% (CONN,ADDR))
While True:
Data_r = SELF.SOCT.RECV (1024) # Accept data from socket
Print ("Received%s from socket"% data_r)
Self.soct.sendall ("data_s") # Send data to the socket
Print ("Send data%s to socket"% data_s)
Self.soct.close () # End the created socket Method.




Python socket (single thread)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.