2-1.面向连接的套接字和无连接的套接字之间的区别是什么?
面向连接的:通信之前必须先建立起一个连接,提供序列化的,可靠的和不重复的数据交付,而没有边界记录。
无连接的:在通信开始之前并不需要建立连接,在数据传输过程中并无法保证它的顺序性,可靠性或重复性。
2-2.用自己的话描述客户端/服务器架构的意思。
服务器就是一系列硬件或软件,为一个或多个客户端(服务的用户)提供所需的“服务”。它存在唯一目的就是等待客户端的请求,并响应它们(提供服务),然后等待更多的请求。
客户端因特定的请求而联系服务器,并发送必要的数据,然后等待服务器的回应,最后完成请求或给出故障的原因。
2-3.TCP和UDP之中,哪种类型的服务器接受连接,并将它们转换到独立的套接字进行客户端通信?
TCP。
2-4.客户端。更新Tcp和Udp客户端,以使得服务器名称无需硬编码到应用程序中。此外,应该允许用户指定主机名和端口号,且如果二者中任何一个或者全部参数丢失,那么应该使用默认值。
[python] view plain copy
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 = GetAddr()
if not Host:
Host = DefaultHOST
if not Port:
Port = DefaultPORT
ADDR = (Host, Port)
tcpCliSock = 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.网络互接和套接字。更新服务器代码,使其具有更多功能,令其能够识别以下命令。
data 服务器返回其当前日期/时间戳
os 获取操作系统信息
ls 列出当前目录文件清单
ls dir 返回dir目录中的文件清单
[python] view plain copy
from socket import *
from 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.使用socket.getservbyname()来确定使用UDP协议的“daytime”服务的端口号。
Socket.getservbyname(‘daytime’,‘udp’)
可得到结果端口为13
2-7.创建一个简单的半双工聊天程序
Server部分:
[python] view plain copy
from socket import *
HOST = ""
PORT =2051
ADDR = (HOST, PORT)
BUFSIZ =1024
tcpSerSock = socket(AF_INET,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)
data =None
tcpCliSock.close()
Client部分:
[python] view plain copy
from socket import *
HOST ='localhost'
PORT =2051
BUFSIZ =1024
ADDR = (HOST, PORT)
tcpCliSock = socket(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.多用户,多房间,全双工聊天
Server部分:
[python] view plain copy
import socket, select
import re
server = socket.socket()
Addr = ("",2050)
server.bind(Addr)
server.listen(5)
inputs = [server]
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] = [client, 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],data
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] == clientdict[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] == clientdict[i][3]:
x.send(senddata)
disconnected =False
except socket.error:
disconnected =True
if disconnected:
leftdata ="%s has left"%clientdict[i][2]
print leftdata
for x in inputs:
if x == server or x == i:
pass
else:
x.send(leftdata)
inputs.remove(i)
Client部分:
[python] view plain copy
from socket import *
import threading
from time import sleep
HOST ='localhost'
PORT =2050
BUFSIZ =1024
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)
data = tcpCliSock.recv(BUFSIZ)
print data
def send():
while True:
data = raw_input(' > ')
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.编写一个Web客户端,连接到一个网站,发送HTTP命令GET/ \n。
[python] view plain copy
from socket import *
HOST ='www.bilibili.com'
PORT =80
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)