python socket程式設計入門級

2022-02-21 21:08:57 字數 1915 閱讀 5392

客戶端

import socket

import time

sk = socket.socket() # 第一步:建立socket物件

address = ('127.0.0.1', 8080) # 協議是ip+埠(型別元組)

sk.connect(address) # 第二步:建立鏈結

while true:

inp = input('客戶端》\n')

if inp == 'exit':

break

sk.send(bytes(inp, 'utf8')) # 第三步:請求資料

time.sleep(1) # low方法防止粘包

data = sk.recv(1024) # 接收確認資訊

print("接收服務端的資料", str(data, 'utf8'))

sk.close()

服務端

import socket

# family type

# af_inet,af_inet6

# af_unix

# sock_stream:: tcp

# sock_dgram :: udp

# sk只負責繫結埠等待鏈結,傳送接收訊息用conn。

sk = socket.socket() # 預設引數tcp

address = ('127.0.1', 8080)

sk.bind(address) # 繫結ip協議和埠

sk.listen(3) # 定義最大可以掛起連線數。

print('服務的waiting.......')

while 1:

conn, addr = sk.accept() # 等待接收來自客戶端的資訊

print(addr)

while 1:

try:

data = conn.recv(1024)

except exception:

break

if not data: break

print('接收到來自客戶端的資訊......', str(data, 'utf8'))

inp = input('》')

conn.send(bytes(inp, 'utf8'))

使用多執行緒版

import socketserver

class myserver(socketserver.baserequesthandler):

# 重寫父類的方法

def handle(self):

print('waiting.......')

while 1:

conn = self.request

print(self.client_address)

while 1:

try:

data = conn.recv(1024)

except exception:

break

if not data:

break

print('......', str(data, 'utf8'))

inp = input('》')

conn.sendall(bytes(inp, 'utf8'))

conn.close()

if __name__ == '__main__':

host = '127.0.0.1'

ip = '8080'

server = socketserver.threadingtcpserver((host, ip), myserver)#多執行緒通話

# 不會出現在乙個客戶端結束後,當前伺服器端就會關閉或者報錯,而是繼續執行,與其他的客戶端繼續進行通話。

server.serve_forever()

Python Socket 程式設計

client import socket,sys if name main 處理引數 argv sys.argv if len argv 3 or len argv 2 and argv 1 print useage argv 0 sys.exit 0 host argv 1 server ip位址...

python socket程式設計

python 編寫server的步驟 1.第一步是建立socket物件。呼叫socket建構函式。如 socket socket.socket family,type family引數代表位址家族,可為af inet或af unix。af inet家族包括internet位址,af unix家族用於...

python socket程式設計

客戶端 author lenovo fromsocketimport host localhost port 2157 bufsize 1024 addr host,port tcpclient socket af inet,sock stream tcpclient.connect addr wh...