缃戠粶缂栫▼ 濂楁帴瀛梥ocket 鍙? 绮樺寘

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了缃戠粶缂栫▼ 濂楁帴瀛梥ocket 鍙? 绮樺寘相关的知识,希望对你有一定的参考价值。

鏍囩锛?a href='http://www.mamicode.com/so/1/except' title='except'>except   鍑芥暟   block   浼犺緭   灏佽   bre   璺緞   瀛樺湪   

缃戠粶缂栫▼ 濂楁帴瀛梥ocket 鍙?绮樺寘

sockt 鍒濊瘑

  • 浜斿眰鍗忚 : 浠庝紶杈撳眰鍖呮嫭浼犺緭灞備互涓?, 閮芥槸鎿嶄綔绯荤粺甯垜浠皝瑁呯殑鍚勭head
  • socket濂楁帴瀛楀厖褰撶殑灏辨槸鍐呯疆妯″潡鐨勮鑹?/li>
  • socket 濂楁帴瀛?瀹冨瓨鍦ㄤ簬浼犺緭灞備笌搴旂敤灞備箣闂寸殑鎶借薄灞?/u>
  • 閬垮厤浣犲涔犲悇灞傜殑鎺ュ彛浠ュ強鍗忚鐨勪娇鐢? socket宸茬粡灏佽濂戒簡鎵€鏈夌殑鎺ュ彛 .
  • 鐩存帴浣跨敤杩欎簺鎺ュ彛鎴栬€呮柟娉曞嵆鍙?, 浣跨敤璧锋潵鏂逛究,鎻愬崌寮€鍙戞晥鐜?/li>
  • socket 灏辨槸涓€涓ā鍧?, 閫氳繃浣跨敤瀛︿範妯″潡鎻愪緵鐨勫姛鑳?, 寤虹珛瀹㈡埛绔笌鏈嶅姟绔殑閫氫俊

濂楁帴瀛楃殑宸ヤ綔娴佺▼锛堝熀浜嶵CP鍜?UDP涓や釜鍗忚锛?/h1>

TCP鍗忚涓嬬殑socket

socket()妯″潡鍑芥暟鐢ㄦ硶

import socket
socket.socket(socket_family,socket_type,protocal=0)
 socket_family 鍙互鏄?AF_UNIX 鎴?AF_INET銆俿ocket_type 鍙互鏄?SOCK_STREAM 鎴?SOCK_DGRAM銆俻rotocol 涓€鑸笉濉?榛樿鍊间负 0銆?
#  鑾峰彇tcp/ip濂楁帴瀛?tcpSock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
tcpSock = socket.socket()  #銆€鎷彿閲屽彲浠ヤ笉鍐欍€€榛樿

#銆€鑾峰彇udp/ip濂楁帴瀛?udpSock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

鐢变簬 socket 妯″潡涓湁澶鐨勫睘鎬с€傛垜浠湪杩欓噷鐮翠緥浣跨敤浜?#39;from module import *'璇彞銆備娇鐢?'from socket import *',鎴戜滑灏辨妸 socket 妯″潡閲岀殑鎵€鏈夊睘鎬ч兘甯﹀埌鎴戜滑鐨勫懡鍚嶇┖闂撮噷浜?杩欐牱鑳?澶у箙鍑忕煭鎴戜滑鐨勪唬鐮併€?渚嬪tcpSock = socket(AF_INET, SOCK_STREAM)


##============鏈嶅姟绔鎺ュ瓧鍑芥暟
s.bind()   #  缁戝畾(涓绘満,绔彛鍙?鍒板鎺ュ瓧
s.listen() #銆€寮€濮婽CP鐩戝惉
s.accept() #銆€琚姩鎺ュ彈TCP瀹㈡埛鐨勮繛鎺?(闃诲寮?绛夊緟杩炴帴鐨勫埌鏉?
##============瀹㈡埛绔鎺ュ瓧鍑芥暟
s.connect()     # 涓诲姩鍒濆鍖朤CP鏈嶅姟鍣ㄨ繛鎺?s.connect_ex()  connect()鍑芥暟鐨勬墿灞曠増鏈?鍑洪敊鏃惰繑鍥炲嚭閿欑爜,鑰屼笉鏄姏鍑哄紓甯?
##============鍏叡鐢ㄩ€旂殑濂楁帴瀛楀嚱鏁?s.recv()          #  鎺ユ敹TCP鏁版嵁
s.send()          #  鍙戦€乀CP鏁版嵁(send鍦ㄥ緟鍙戦€佹暟鎹噺澶т簬宸辩缂撳瓨鍖哄墿浣欑┖闂存椂,鏁版嵁涓㈠け,涓嶄細鍙戝畬)
s.sendall()         鍙戦€佸畬鏁寸殑TCP鏁版嵁(鏈川灏辨槸寰幆璋冪敤send,sendall鍦ㄥ緟鍙戦€佹暟鎹噺澶т簬宸辩缂撳瓨鍖哄墿浣欑┖闂存椂,鏁版嵁涓嶄涪澶?寰幆璋冪敤send鐩村埌鍙戝畬)
s.recvfrom()        鎺ユ敹UDP鏁版嵁
s.sendto()          鍙戦€乁DP鏁版嵁
s.getpeername()     杩炴帴鍒板綋鍓嶅鎺ュ瓧鐨勮繙绔殑鍦板潃
s.getsockname()     褰撳墠濂楁帴瀛楃殑鍦板潃
s.getsockopt()      杩斿洖鎸囧畾濂楁帴瀛楃殑鍙傛暟
s.setsockopt()      璁剧疆鎸囧畾濂楁帴瀛楃殑鍙傛暟
s.close()          # 鍏抽棴濂楁帴瀛?
闈㈠悜閿佺殑濂楁帴瀛楁柟娉?s.setblocking()     璁剧疆濂楁帴瀛楃殑闃诲涓庨潪闃诲妯″紡
s.settimeout()      璁剧疆闃诲濂楁帴瀛楁搷浣滅殑瓒呮椂鏃堕棿
s.gettimeout()      寰楀埌闃诲濂楁帴瀛楁搷浣滅殑瓒呮椂鏃堕棿

闈㈠悜鏂囦欢鐨勫鎺ュ瓧鐨勫嚱鏁?s.fileno()          濂楁帴瀛楃殑鏂囦欢鎻忚堪绗?s.makefile()        鍒涘缓涓€涓笌璇ュ鎺ュ瓧鐩稿叧鐨勬枃浠?/code>

# server绔? import socket phone = socket.socket(socket.AF_INET,socket.SOCK_STREAM) # 鍒涘缓socket 瀵硅薄 phone.bind(('127.0.0.1',8080)) # 8000 ~ 65535 缁戝畾ip鍦板潃鍜岀鍙? phone.listen(5) # TCP 寮€濮嬬洃鍚? # conn鐩稿綋浜庣閬? conn, client_addr = phone.accept() # 琚姩鎺ュ彈TCP瀹㈡埛鐨勮繛鎺?(闃诲寮?绛夊緟杩炴帴鐨勫埌鏉?print(conn, client_addr, sep='\n') # 鎵撳嵃閫氶亾 鍜?瀹㈡埛绔殑鍦板潃 from_client_data = conn.recv(1024) # 姣忔 鎺ユ敹 瀹㈡埛绔唴瀹?鐨?鏈€澶ч檺鍒?1024 bytes print(from_client_data.decode('utf-8')) conn.send(from_client_data.upper()) # 鍚戝鎴风鍙戦€?淇℃伅 conn.close() # 鎸傜數璇? phone.close() # 鍏抽棴濂楁帴瀛?/code>
# client
import socket

phone = socket.socket(socket.AF_INET,socket.SOCK_STREAM)  # 涔扮數璇?
phone.connect(('127.0.0.1',8080))  # 涓庡鎴风寤虹珛杩炴帴锛?鎷ㄥ彿

phone.send('hello'.encode('utf-8'))

from_server_data = phone.recv(1024)

print(from_server_data.decode('utf-8'))

phone.close()  # 鎸傜數璇?/code>

绗簩鐗堬紝閫氫俊寰幆

# server
import socket

photo = socket.socket()

photo.bind(('127.0.0.1',8080))

phone.listen(5)

conn, client_addr = phone.accept()
print(conn, client_addr, sep='\n')

while 1:  # 寰幆鏀跺彂娑堟伅
    try:
        from_client_data = conn.recv(1024)
        print(from_client_data.decode('utf-8'))
    
        conn.send(from_client_data + b'SB')
    
    except ConnectionResetError:
        break

conn.close()
phone.close()
# client
import socket

phone = socket.socket(socket.AF_INET,socket.SOCK_STREAM)  # 涔扮數璇?
phone.connect(('127.0.0.1',8080))  # 涓庡鎴风寤虹珛杩炴帴锛?鎷ㄥ彿


while 1:  # 寰幆鏀跺彂娑堟伅
    client_data = input('>>>')
    phone.send(client_data.encode('utf-8'))
    
    from_server_data = phone.recv(1024)
    
    print(from_server_data.decode('utf-8'))

phone.close()  # 鎸傜數璇?/code>

绗笁鐗?閫氫俊 / 杩炴帴寰幆 ***

# server
import socket

phone = socket.socket()
phone.bind(('127.0.0.1', 8080))

phone.listen(5) 

while 1:  # 寰幆杩炴帴瀹㈡埛绔?    conn, client_addr = phone.accept()
    print(conn,client_addr)

    while 1:
        try:
            from_client_data = conn.recv(1024)
            print(from_client_data.decode('utf-8'))

            conn.send(from_client_data + b'SB')

        except ConnectionResetError:
            break

    conn.close()
phone.close()
# client
import socket

phone = socket.socket(socket.AF_INET,socket.SOCK_STREAM)  # 涔扮數璇?
phone.connect(('127.0.0.1',8080))  # 涓庡鎴风寤虹珛杩炴帴锛?鎷ㄥ彿


while 1:
    client_data = input('>>>')
    phone.send(client_data.encode('utf-8'))
    
    from_server_data = phone.recv(1024)
    
    print(from_server_data.decode('utf-8'))

phone.close()  # 鎸傜數璇?/code>

# server import socket import subprocess phone = socket.socket(socket.AF_INET,socket.SOCK_STREAM) phone.bind(('127.0.0.1',8080)) phone.listen(5) while 1 : # 寰幆杩炴帴瀹㈡埛绔? conn, client_addr = phone.accept() print(client_addr) while 1: try: cmd = conn.recv(1024) ret = subprocess.Popen(cmd.decode('utf-8'),shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE) correct_msg = ret.stdout.read() error_msg = ret.stderr.read() conn.send(correct_msg + error_msg) except ConnectionResetError: break conn.close() phone.close()
# client
import socket

phone = socket.socket(socket.AF_INET,socket.SOCK_STREAM)  # 涔扮數璇?
phone.connect(('127.0.0.1',8080))  # 涓庡鎴风寤虹珛杩炴帴锛?鎷ㄥ彿


while 1:
    cmd = input('>>>')
    phone.send(cmd.encode('utf-8'))
    
    from_server_data = phone.recv(1024)
    
    print(from_server_data.decode('gbk'))

phone.close()  # 鎸傜數璇?

绮樺寘

绮樺寘姒傚康

  • 绮樺寘鍙細鍑虹幇鍦╰cp浼犺緭涓? 鏄袱绉嶄笉鍚岀殑鏁版嵁杩炴帴鍦ㄤ竴璧锋棤娉曟甯稿垎绂?灏变細鍑虹幇绮樺寘

绮樺寘鐜拌薄

  • 绮樺寘鐜拌薄鐨勬牴鏈師鍥?: 绯荤粺缂撳啿鍖?/li>
'''                鏈嶅姟绔?    鍙戝嚭                      瀹㈡埛绔? 鎺ユ敹
绗竴娆ir          鏁版嵁418 < 1024 鏁版嵁鍏ㄩ儴鍙戝嚭           鏁版嵁鍏ㄩ儴鎺ユ敹   
绗簩娆pconifg     鏁版嵁1517 > 1024 鏁版嵁鍙彂閫?024涓瓧鑺? 鏁版嵁鍙帴鏀?024涓瓧鑺?绗笁娆?dir         鏁版嵁418 < 1024 鏁版嵁鏄皝?             鏁版嵁鎺ユ敹493涓瓧鑺?'''       

绯荤粺缂撳啿鍖?/h2>

缂撳啿鍖虹殑瀹氫箟

  • 缂撳啿鍖烘槸鍐呭瓨涓殑涓€鍧楀尯鍩?/li>

缂撳啿鍖虹殑浣滅敤

  • 濡傛灉浣犵殑缃戠粶鍑虹幇鐭殏鐨勫紓甯告垨鑰呮尝鍔ㄦ帴鏀舵暟鎹氨浼氬嚭鐜扮煭鏆傜殑涓柇,褰卞搷浣犱笅杞芥垨鑰呬笂浼犵殑鏁堢巼
  • 缂撳啿楂橀€熻澶囦笌浣庨€熻澶囦箣闂寸殑閫熷害宸紓,灏眘ocket鐨勭紦鍐插尯鑰岃█,缂撳啿鍖虹殑浣滅敤灏辨槸閲婃斁cpu,浣縞pu涓嶇敤鏃跺埢鎺ユ敹鍙戞潵鐨勬暟鎹?cpu鍙渶瑕佸湪缂撳啿鍖轰腑鏈夋暟鎹椂鎵嶅幓鎺ュ彈鏁版嵁
  • 浣嗘槸 鍑′簨閮芥槸鍙屽垉鍓?/u> , 缂撳啿鍖鸿В鍐充簡涓婁紶涓嬭浇鐨勪紶杈撴晥鐜囩殑闂 , 鍚屾椂甯︽潵浜嗙矘鍖呯幇璞?/li>

鎻愰珮涓婁紶涓嬭浇鐨勬晥鐜?, 淇濇寔绋冲畾鎬?, 閲婃斁cpu ,鍑忓皯涓庣鐩樼殑浜や簰

鐢╨en鑾峰彇bytes鐨勬€诲瓧鑺傛暟

s1 = "alexsb"

b1 = s1.encode("utf-8")

print(b1)

print(len(b1)) # 6 len  鍙互璁$畻 utf-8 鐨?瀛楄妭鏁?

import struct

import struct
# 灏嗕竴涓暟瀛楄浆鍖栨垚绛夐暱搴︾殑bytes绫诲瀷銆?ret = struct.pack('i', 183346)
print(ret, type(ret), len(ret))       # b'2\xcc\x02\x00'   <class 'bytes'>   4

# 閫氳繃unpack鍙嶈В鍥炴潵
ret1 = struct.unpack('i',ret)
print(ret1,type(ret), len(ret))       #  (183346,)         <class 'bytes'>   4
print(ret1[0])

# 浣嗘槸閫氳繃struct 澶勭悊涓嶈兘澶勭悊澶ぇ
#
ret2 = struct.pack('i', 1234567890)   # 鏋侀檺闀垮害 鍐嶉暱灏辨姤閿?print(ret2, type(ret2), len(ret2))    #  b'\xd2\x02\x96I' <class 'bytes'>  4

# 鎶ラ敊闀垮害
ret2 = struct.pack('i', 12345678900)  # 鏋侀檺闀垮害 鍐嶉暱灏辨姤閿?print(ret2, type(ret2), len(ret2))    # 鎶ラ敊
  • 鎬荤粨 : 灏?len 涓?struct 缁撳悎浣跨敤

# server 妯℃嫙杩滅▼鎺у埗涓绘満cmd鍛戒护 import socket import struct import subprocess server = socket.socket() server.bind(('127.0.0.1', 8080)) server.listen(5) while 1: while 1: conn, addr = server.accept() try: cmd = conn.recv(1024) obj = subprocess.Popen(cmd.decode('utf-8'), shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) ret = obj.stdout.read() + obj.stderr.read() print(f'鍑嗗鍙戦€亄len(ret)涓瓧鑺?#39;) ret_len = struct.pack('i',len(ret)) # 鍖呰鍥哄畾4涓瓧鑺?鎶ュご conn.send(ret_len) # 鍙戦€佹姤澶? conn.send(ret) # 鍙戦€佺湡瀹炴暟鎹? except Exception: break conn.close() server.close() # 浣嗘槸low鐗堟湰鏈夐棶棰橈細 # 1锛屾姤澶翠笉鍙湁鎬绘暟鎹ぇ灏忥紝鑰屾槸杩樺簲璇ユ湁MD5鏁版嵁锛屾枃浠跺悕绛夌瓑涓€浜涙暟鎹€?# 2锛岄€氳繃struct妯″潡鐩存帴鏁版嵁澶勭悊锛屼笉鑳藉鐞嗗お澶с€?
# client
import socket
import struct
client = socket.socket()
client.connect(('127.0.0.1', 8080))
while 1:
    cmd = input(">>>").strip()
    client.send(cmd.encode('utf-8'))  # 鍙戦€佸懡浠?    from_server_head = client.recv(4) # 鎺ユ敹server鍖呰杩囩殑鍥哄畾鎶ュご
    from_server_head_int = struct.unpack('i',from_server_head)[0] # 鍙嶅簭鍒楁姤澶存槸 鍏冪粍 , +[0]鎵嶆槸鎶ュご
    # 瑙f瀽鎶ュご 
    print(f'鍑嗗鎺ユ敹from_server_head_int涓瓧鑺?#39;)
    from_server_data = b''
    while from_server_head_int > len(from_server_data):
        from_server_data +=  client.recv(1024)  # 鎺ユ敹鐪熷疄鏁版嵁
        print(from_server_data.decode('gbk'))  
        print(f'瀹㈡埛绔帴鏀朵簡len(from_server_data)涓瓧鑺?#39;)
client.close()

闂涓€

  • 闈炲父澶х殑鏁版嵁 鐩存帴鐢╯truct 浼氭姤閿?/li>

鏂规硶浜?鏃楄埌鐗?/ 鍙嚜瀹氬埗鎶ュご鐗?/h2>

浼犺緭娴佺▼

鏁翠釜娴佺▼鐨勫ぇ鑷磋В閲婏細
鎴戜滑鍙互鎶? 锛屽瓧鍏搁噷鍖呭惈灏嗚鍙戦€佺殑鐪熷疄鏁版嵁鐨勬弿杩颁俊鎭?澶у皬鍟婁箣绫荤殑)锛岀劧鍚?json搴忓垪鍖?/u>锛岀劧鍚庣敤 struck 灏嗗簭鍒楀寲鍚庣殑鏁版嵁闀垮害鎵撳寘鎴?