python socket簡單的c s示例

2021-09-12 11:16:30 字數 1265 閱讀 4906

客戶端和服務端其實是對等的。只不過服務端是bind乙個位址,客服端是connect乙個位址。另外服務端需要呼叫listen()函式使得服務端可以接受連線請求。sendsendall,recv等等是兩邊都可以用的。下面是示例。

server.py

import socket

s = socket.socket(socket.af_inet, socket.sock_stream)

s.bind(

(socket.gethostname(),

1234))

s.listen(5)

while

true

: socketclient, address = s.accept(

)print

(f"connection of is established!"

) data = socketclient.recv(

1024

) data = data.decode(

"utf-8"

) socketclient.send(

bytes

(f"hi , welcome to server!"

,"utf-8"))

socketclient.close

client.py

import socket

s = socket.socket(socket.af_inet, socket.sock_stream)

s.connect(

(socket.gethostname(),

1234))

s.sendall(

bytes

("raines"

,"utf-8"))

full_msg =

""while

true

: st = s.recv(8)

iflen

(st)

<=0:

break

st = st.decode(

"utf-8"

) full_msg += st

print

(full_msg)

簡單的python socket程式設計

最近寫點小東西,要用到socket伺服器和客戶端,用python實現起來非常的方便。貼點 首先 引用必要的包 import thread from socket import from time import ctime接下來定義埠號和位址 host port 8888 埠號 bufsize 200...

python socket 簡單程式設計

伺服器端 import socket s socket.socket host socket.gethostname port 1234 s.bind host,port s.listen 5 while true c,addr s.accept print got connection from ...

Python Socket寫的簡單Server

一 python server 是藍色部分,注釋為黑色字型 color blue usr bin python import socket import re import os color 第一步是建立socket物件。呼叫socket建構函式 socket socket.socket famil...