Simple examples

Simple examples

Server

We use the socket module  socket  function to create a socket object. socket object can be set via a socket service call other functions.

Now we can call  bind (hostname, port)  to the specified service function  port (port) .

Then, we call the socket object's  accept  method. The method waits for client connections, and return  connection  object representing the connection is to the client.

The complete code is as follows:

# ! / Usr / bin / Python 
# - * - Coding: UTF-8 - * - 
# File name: server.py 
 
Import socket                # import socket module 
 
S = socket.socket ()          # Create a socket object 
host = socket.gethostname ( ) # get local host name 
port = 12345                 # set the port 
s.bind ((host, port))         # bind port 
 
s.listen ( 5)                  # wait for the client to connect 
the while True: 
    c, addr = s.accept ()      # establish client connections 
    Print  ' connection address: ' , addr 
    c.send ( ' Welcome to the rookie tutorial! ' ) 
    c.close ()                 # close the connection

Client

Next we write a simple client to connect to the service instance created above. Port number is 12345.

socket.connect (hosname, port)  method opens a TCP connection to the host for the  hostname  port to  port  service providers. After connecting we can get data from the server, remember, after the completion of the operation need to close the connection.

The complete code is as follows:

# ! / Usr / bin / Python 
# - * - Coding: UTF-8 - * - 
# File name: client.py 
 
Import socket                # import socket module 
 
S = socket.socket ()          # Create a socket object 
host = socket.gethostname ( ) # get local host name 
port = 12345                 # set the port number 
 
s.connect ((host, port)) 
Print s.recv (1024 ) 
S.CLOSE ()

 

Guess you like

Origin www.cnblogs.com/furuihua/p/11295649.html