python网络编程之TCP通信实例

时间:2021-04-01 23:59:42

一.

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