Python core Programming (third edition) after-school problem solving--chapter II

Source: Internet
Author: User

Python core Programming (third edition), after-school problem solving, chapter two. All the answers are for bloggers to write their own, because the level is limited, welcome to put forward opinions, mutual exchanges.

2-1. What is the difference between a connection-oriented socket and a connectionless socket.

Connection-oriented: Before communication, a connection must be established to provide serialized, reliable, and repeatable data deliveries without boundary records.

Connectionless: There is no need to establish a connection before the communication begins, and it is not guaranteed to be sequential, reliable or repeatable in the data transfer process.


2-2. Describe what the client/server architecture means in your own words.

A server is a series of hardware or software that provides the required "services" for one or more clients (users of the service). It has the sole purpose of waiting for requests from clients, responding to them (providing services), and then waiting for more requests.

The client contacts the server for a specific request and sends the necessary data, then waits for a response from the server to finalize the request or give the reason for the failure.


In 2-3.tcp and UDP, which type of server accepts connections and converts them to separate sockets for client communication.

Tcp.


2-4. Client. Update the TCP and UDP clients so that the server name does not need to be hard-coded into the application. In addition, you should allow the user to specify the host name and port number, and if either or all of the parameters are missing, the default value should be used.

From socket import *

defaulthost = ' localhost '
defaultport = 1236
Bufsiz = 1024
def getaddr ():
    Host = Raw_input ("Please input host:")
    port = raw_input (' Please input Port: ') return
    host, int (port)

host, port = Ge TADDR ()

if not host:
    host = Defaulthost
if not port:
    port = defaultport

ADDR = (host, Port)

t Cpclisock = socket (af_inet, sock_stream)
Tcpclisock.connect (ADDR) while

True:
    data = raw_input (' > '
    if not data: Break
    tcpclisock.send (data)
    data = Tcpclisock.recv (bufsiz)
    print Data

Tcpclisock.close ()


2-5. Network interconnection and sockets. Update the server code so that it has more functionality to enable it to recognize the following commands.

The data server returns its current date/time stamp

OS Get operating System Information

LS lists the current directory file list

ls dir returns the list of files in the Dir directory

From socket import * to time
import ctime
import OS
import re

HOST = ""
PORT = 1240
ADDR = (HOST , PORT)
bufsiz = 1024

tcpsersock = socket (af_inet,sock_stream)
tcpsersock.bind (ADDR)
Tcpsersock.listen (5)
responsedic = {' Data ': CTime (), ' OS ': os.name, ' ls ': str (Os.listdir (OS.CURDIR))} while

True:
    print "Waiting for connect ..."
    tcpclisock, addr = tcpsersock.accept ()
    print ' ... connected from: ', Addr while

    True:
        data = TCPCLISOCK.RECV (bufsiz)
        Findre = Re.match (R ' LS dir\ ((. +) \) ', data "
        if not Data:
            break
        elif responsedic.get (data):
            tcpclisock.send (responsedic[data))        
        elif Findre:
            Print Os.listdir (Findre.group (1))
            tcpclisock.send (str (Os.listdir (Findre.group (1)))            
        else:
            Tcpclisock.send (str (data))
    tcpclisock.close ()
tcpclisock.close ()


2-6. Use Socket.getservbyname () to determine the port number of the "daytime" service that uses the UDP protocol.

Socket.getservbyname (' daytime ', ' UDP ')

Can get the result port of 13

2-7. Create a simple half-duplex chat program

Server section:

From socket import *

HOST = ""
PORT = 2051
ADDR = (HOST, PORT)
bufsiz = 1024
tcpsersock = socket (af_in Et,sock_stream)
tcpsersock.bind (ADDR)
Tcpsersock.listen (5) while

True:
    print waiting for Connect ... "
    tcpclisock, addr = tcpsersock.accept ()
    print ' ... connected from: ', addr while
    True:
        data = TCPCLISOCK.RECV (bufsiz)
        if data = = ' Quit ':
            tcpclisock.close ()
        else:
            print "%s said:%s"% (addr, Data)
        SendData = "" while
        senddata = = "":
            senddata = raw_input (' > ')
        tcpclisock.send (SendData) C23/>data = None
tcpclisock.close ()
Client section:

From socket import *
HOST = ' localhost '
PORT = 2051
bufsiz = 1024
ADDR = (HOST, PORT)

Tcpclisock = Soc Ket (Af_inet,sock_stream)
Tcpclisock.connect (ADDR) while

True:
    data = raw_input (' > ')
    if not data:
        continue
    tcpclisock.send (data)
    data = Tcpclisock.recv (bufsiz)
    print Data

Tcpclisock.close ()

2-8,2-9,2-10, multi-user, multiple rooms, full duplex chat

Server section:

Import socket, select Import RE server = Socket.socket () Addr = ("", 2050) Server.bind (ADDR) Server.listen (5) inputs = [SE RVer] clientdict = {} user = "No name user" Roomnumber = 0 print "Start the chat server ..." while True:rs, WS, ES =  Select.select (inputs, [], []) for i in rs:if i = = server:client, addr = I.accept () # print ' Connected from ', addr, ' This is user%s '%user inputs.append (client) clientdict[client] = [CLI  ent, addr, user, Roomnumber] else:try:data = I.RECV (1024) matchname
                = Re.match (R ' (. +) \sjoin The server ', data) Matchroom = Re.match (R ' Join the Room (\d) ', data) If matchname:print data for x in inputs:if x = = Server or x = = I:pass Else:if clientdict[x][2] = = "No name user" or CLIENTDICT[X][3] = = 0:pass Else:
                    X.send (data) Username = Matchname.group (1) clientdict[i][2] = Username I.send (' welcome,%s '%username) elif matchroom:print '%s '%clientdict[i][2],da
                    Ta roomnumber = matchroom.group (1) clientdict[i][3] = Roomnumber I.send (' You join room%s '%roomnumber] for x in inputs:if x = = Server or x = = I:pass Else:if clientdict[x][3] = = CLI
                    ENTDICT[I][3]: X.send ('%s Join this room '%clientdict[i][2]) Else:
                        SendData = "%s said:%s"% (clientdict[i][2], data) for x in inputs: if x = = Server or x = i: Pass Else:if clientdict[x][3] = = Client DICT[I][3]: x.send (senddata) disconnected = False except sock et.error:disconnected = True If Disconnected:leftdata = "%s has left"%clie 
                        NTDICT[I][2] Print Leftdata for x in inputs:if x = = = Server or x = = I: Pass Else:x.send (Leftdata) inputs.re Move (i)
Client section:

From socket Import *
import threading to time
import sleep
HOST = ' localhost '
PORT = 2050
Bufsiz = 1 024
ADDR = (HOST, PORT)

Tcpclisock = socket (af_inet,sock_stream)
tcpclisock.connect (ADDR)
username = Raw_input ("Please set your username:")
tcpclisock.send ("%s join the server"%username)
data = Tcpclisock.recv (Bufsiz)
Print data
room = raw_input ("Input room number (input a number 1-9):")
tcpclisock.send ("Join the room%s"%room) C15/>data = Tcpclisock.recv (bufsiz)
print data
def send (): While
    True:
        data = raw_input (' > ') C20/>if not data:
            continue
        Else:
            tcpclisock.send (data)
    
def receive (): While
    True:
        data = Tcpclisock.recv (bufsiz)
        print data
        print ' > ',

t1 = threading. Thread (target = send)
t2 = Threading. Thread (target = receive)
T1.start ()
T2.start ()
t1.join ()
t2.join ()

tcpclisock.close ()
2-11. Write a Web client, connect to a Web site, send HTTP commands get/\ n.

From socket import *
HOST = ' www.bilibili.com '
PORT =
Bufsiz = 1024
ADDR = (HOST, PORT)
Tcpclisock = Socket (af_inet,sock_stream)
tcpclisock.connect (ADDR)
tcpclisock.send (' get/\ n ')
data = TCPCLISOCK.RECV (Bufsiz)
with open (r "D:\webpage.txt", ' W ') as F:
    f.write (data)


(not finished)

Related Article

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.