python,socket网络编程,最简单的server端和client端代码

千锋 2019-12-11

python网络编程三要素:网络地址,端口号,协议

知识点:conn代表的是客户端的socket对象.

下面的server.py和client.py小程序,实现了最简单的socket通信功能.

#server.py
import socket
sk = socket.socket()
address = (‘127.0.0.1‘,8080)
sk.bind(address)
sk.listen(3)
print(‘waitting......‘)
conn,addr = sk.accept()
inp = input(‘>>>>>>‘)
conn.send(bytes(inp,‘utf8‘))
data = conn.recv(1024)
print(data)
sk.close()
import socket
sk = socket.socket()
address = (‘127.0.0.1‘,8080)
sk.connect(address)
data = sk.recv(1024)
print(data)
sk.send(bytes(‘You are stupid‘,‘utf8‘))

server.py运行结果:

/usr/bin/python3.6 /home/guoming/python/day26/server.py
waitting......
>>>>>>hello
b‘You are stupid‘

Process finished with exit code 0

client.py运行结果:

/usr/bin/python3.6 /home/guoming/python/day26/client.py
b‘hello‘

Process finished with exit code 0

相关推荐