python socket編程功能

socket編程基本思路

服務器端

  1. 建立socket, 綁定socket到本地IP, 端口 socket.socket(socket.AF_INET,socket.SOCK_STREAM), s.bind()
  2. 開始監聽鏈接 s.listen()
  3. 進入循環,不斷接受客戶端的鏈接請求 s.accept()
  4. 而後接收傳來的數據,併發送給對方數據 s.recv() , s.sendall()
  5. 傳輸完畢後,關閉socket

客戶端

  1. 建立套接字,鏈接遠端地址 #socket.socket(socket.AF_INET,socket.SOCK_STREAM), s.connect()
  2. 鏈接後發送數據和接收數據 #s.sendall(), s.recv()
  3. 傳輸完畢後,關閉套接字 #s.close()
# 導入socket庫:
import socket
# 建立一個socket:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 創建鏈接:
s.connect(('www.sina.com.cn', 80))

建立socket時, socket.AF_INET表明使用用IPv4協議, 若是要使用IPv6協議, 則指定sockt.AF_INET6, SOCK_STREAM指定使用面向流的TCP協議.html

s.send(b'GET / HTTP/1.1\r\nHost: www.sina.com.cn\r\nConnection: close\r\n\r\n')

# 接收數據:
buffer = []
while True:
    # 每次最多接收1k字節:
    d = s.recv(1024)
    if d:
        buffer.append(d)
    else:
        break
data = b''.join(buffer)

# 關閉鏈接:
s.close()


# 處理數據
header, html = response.split(b'\r\n\r\n', 1)
print(header.decode("utf-8"))
print(html.decode('utf-8'))

socket 併發

socket默認是堵塞的, 當socket運行connect(),recv()方法時, 會堵塞直到運行完成.python

sock = socket.socket()
#將socket設爲非堵塞的self.
sock.setblocking(False)

這樣作會直接拋出一個BlockingIOError的異常, 詳細內容A non-blocking socket operation could not be completed immediately,編程

解決方法:服務器

try:
    sock.connect(('xkcd.com', 80))
except BlockingIOError:
    pass
request = 'GET {} HTTP/1.0\r\nHost: xkcd.com\r\n\r\n'.format(url)
encoded=request.encode('ascii')
sock.send(encoded)

也會拋出異常OSError: A request to send or receive data was disallowed because the socket is not connected and (when sending on a datagram socket using a sendto call) no address was suppliedmarkdown

解決方法:併發

while True:
    try:
        sock.send(encoded)
        break  # Done.
    except OSError as e:
        pass
相關文章
相關標籤/搜索