18.5 TCP的半关闭
TCP提供了连接的一端的结束它的发送后还能接收另一端数据的能力。
这就是所谓的半关闭
print(socket.SHUT_RDWR)
print(socket.SHUT_RD)
print(socket.SHUT_WR)
2
0
1
0是READ,1是WRITE,2是READ WRITE
如果应用程序不调用c l o s e而调用s h u t d o w n,且第2个参数值为1,则插口的A P I支持
半关闭。然而,大多数的应用程序通过调用close终止两个方向的连接。
node1:/root/test#cat t2.py
# coding = utf-8
# -*- coding:utf-8 -*-
import socket
ip_port = ('192.168.137.2',8080)
BUFSIZE = 1000
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)#创建套接字
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(ip_port)#绑定地址
s.listen(5)#监听链接
print('server listening8080...')
while True: #无限等待连接
conn,addr = s.accept() #接受客户端连接
print(conn)
print(addr)
print('接到来自%s的链接'%addr[0])
while True: #通信循环,无限接受客户端信息
#print conn.getpeername()
try:
peeraddr=conn.getpeername()
msg = conn.recv(BUFSIZE) #接受消息的内容
except:
break;
if len(msg)==0:break #如果 不加,已连接的客户端突然断开,recv不再阻塞发生死循环
print '-----------------------'
print msg
print '-----------------------'
try:
conn.send('response:'+msg)
except:
print '555555555'
#conn.send(msg.upper())#服务端发送消息
conn.close()#关闭链接
s.close()#关闭套接字
import socket
import time
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.connect(("192.168.137.2",8080))
s.settimeout(10)
s.send('3232344dd')
#print s.getsockopt()
print s.getsockname()
print s.getpeername()
#s.sendall("this is shutdown test" + "\r\n")
print dir(socket.herror)
print(socket.SHUT_RDWR)
print(socket.SHUT_RD)
print(socket.SHUT_WR)
#print s.recv(90)
s.send('2121212121')
print s.recv(90)
s.shutdown(1)
#time.sleep(10)
#print s.recv(90)
time.sleep(30)
#s.send('xxxxxxxx')
print s.recv(90)
s.send('99999888')
# while (1==1):
# print s.recv(90)
C:\Python27\python.exe C:/Users/TLCB/PycharmProjects/untitled2/http/t5.py
('192.168.137.1', 58945)
('192.168.137.2', 8080)
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__getitem__', '__getslice__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setstate__', '__sizeof__', '__str__', '__subclasshook__', '__unicode__', '__weakref__', 'args', 'errno', 'filename', 'message', 'strerror']
2
0
1
response:3232344dd
Traceback (most recent call last):
File "C:/Users/TLCB/PycharmProjects/untitled2/http/t5.py", line 26, in <module>
s.send('99999888')
socket.error: [Errno 10058]
response:2121212121
Process finished with exit code 1
来源:CSDN
作者:zhaoyangjian724
链接:https://blog.csdn.net/zhaoyangjian724/article/details/104473845