Python程序设计之网络编程(2)
程序员文章站
2022-04-12 16:14:45
...
1.使用TCP实现终端通信
①服务器端
import socket
def main():
words={"Hello":"Hello","Hi":"Hi"}
HOST=''
PORT=50007
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
#绑定socket
s.bind((HOST,PORT))
#监听
s.listen(1)
print('Listening at port:',PORT)
conn,addr=s.accept()
print('Connect by:',addr)
while True:
data=conn.recv(1024)
data=data.decode()
if not data:
break
print('Received message:',data)
conn.sendall(words.get(data,'Nothing').encode())
conn.close()
s.close()
if __name__ == '__main__':
main()
②客户端
import socket
import sys
def main():
#服务器端IP
HOST='127.0.0.1'
#服务器端端口号
PORT=50007
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
try:
s.connect((HOST,PORT))
except Exception as e:
print('Server not found or not open!')
sys.exit()
while True:
c=input('Input the content you want to send:')
#发送数据
s.sendall(c.encode())
#从服务器端接受数据
data=s.recv(1024)
data=data.decode()
print('Received:',data)
if c.lower()=='bye':
break
s.close()
if __name__ == '__main__':
main()
2.学习笔记
1.客户端连接方式,使用元组形式建立连接
s.connect((HOST,PORT))
2.服务器端使用元组形式绑定端口号和端口
#绑定socket
s.bind((HOST,PORT))
3.初始化套接字:
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
4.从服务器端接收数据
data=conn.recv(1024)
上一篇: 如何汉化eclipse(有图有真相)
下一篇: [Python] 虚拟环境