python網絡編程之TCP通信實例


一.

server.py

import socket
host="localhost"
port=10000
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.bind((host,port))
s.listen(5)
while(1):
    sock,addr=s.accept()
    print("got connection form ",sock.getpeername())
    sock.send('Hello!')
    data=sock.recv(1024)
    if not data:
        print("no client")
    else:
        print(data)

輸出

('got connection form ', ('127.0.0.1', 56547))
{"req": "add", "obj": "nav", "param": {"marker": "mark_name"}, "seq": 0}exitbye bye

 

client.py

import socket
import json
import time
host="localhost"
port=10000
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.connect((host,port))
data={"req":"add","obj":"nav","seq":0,"param":{"marker":"mark_name"}}
j = json.dumps(data)
s.send(j)

print("fff")
s.send('exit')
s.send('bye bye')
print("dddd")
#print(s.recv(1024))
time.sleep(5)
s.close()

輸出

fff
dddd

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM