Chapter 14 of python, Network Programming

Source: Internet
Author: User

I. socket module

There are two types of sockets: Server, client,

Create a socket and wait for the connection

Server:

import sockets = socket.socket()port = 1234host = socket.gethostname()print hosts.bind((host,port))s.listen(5)while True:    get,addr = s.accept()    print 'Got connection from',addr    get.send('Thank you for connecting')    get.close()

Client:

import sockets = socket.socket()host = socket.gethostname()port = 1234s.connect((host,port))print s.recv(1024)

>>>
Z5WRYRLDY59AL03
Got connection from ('2017. 27.174.175 ', 222)
Got connection from ('2017. 27.174.175 ', 222)
Got connection from ('2017. 27.174.175 ', 222)
Got connection from ('2017. 27.174.175 ', 222)

>>>================================== RESTART ==== ======================================
>>>
Thank you for connecting
>>>================================== RESTART ==== ======================================
>>>
Thank you for connecting
>>>================================== RESTART ==== ======================================
>>>
Thank you for connecting
>>>================================== RESTART ==== ======================================
>>>
Thank you for connecting

Ii. urllib and urllib2

You can access the file through the network, and use urllib for simple download using a URL. If you want to use http verification or urllib2 using cookies

1. Open a Remote File

From urllib import urlopen

Webpage = urlopen ("http://www.baidu.com ")

Urlopen method: close, read, readline, readlines

2. obtain remote files

Urlretrieve ('HTTP: // www.python.org ', 'c: \ python.html ')

By default, it is placed in a temporary location and cleared with urlcleanup

3. SocketServer

SocketServer is the basis of many server frameworks, such as BaseHTTPServer, SimpleHTTPServer, and CGIHTTPServer.

SocketSever contains four basic classes: 1 TCPServer for TCP socket stream, 2. UDPServer for UDP datagram 3. UnixStreamServer 4. UnixDatagramServer

Server:

from SocketServer import TCPServer,StreamRequestHandlerimport socketclass Handler(StreamRequestHandler):    def handle(self):        addr = self.request.getpeername()        print 'Got connection from',addr        self.wfile.write('Thank you for connecting!!!')host = socket.gethostname()server = TCPServer((host,1234),Handler)server.serve_forever()
>>>
Thank you for connecting !!!
>>>

Got connection from ('2017. 27.174.175 ', 222)

4. Multiple connections

Three methods: forking, threading, and asynchronous I/O)

Use SocketServer for forks and thread processing

from SocketServer import TCPServer,ForkingMixIn,StreamRequestHandlerimport socketclass Server(ForkingMixIn,TCPServer):passclass Handler(StreamRequestHandler):    def handle(self):        addr = self.request.getpeername()        print 'Got connection from',addr        self.wfile.write('Thank you for connecting ...')host = socket.gethostname()server = Server(('',1234),Handler)server.serve_forever()

Use select

import socket,selects = socket.socket()host = socket.gethostname()port = 3306print hosts.bind((host,port))s.listen(5)inputs = [s]while True:    rs,ws,es = select.select(inputs,[],[])    for r in rs:        if r is s:            c,addr = s.accept()            print 'Got connection form',addr            inputs.append(c)        else:            try:                data = r.recv(1024)                disconnected = not data                if data:                    r.send('yes!I can hear you!')            except socket.error:                disconnected = True            if disconnected:                print r.getpeername(),'disconnected'                inputs.remove(r)            else:                print data




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.