python_socket_tcp
程序员文章站
2022-07-08 07:57:35
# -*- coding:utf-8 -*-
import socket
HOST='127.0.0.2' #服务端的IP地址
PORT=50007 #...
# -*- coding:utf-8 -*- import socket HOST='127.0.0.2' #服务端的IP地址 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()
server
# -*- coding: utf-8 -*- # TCP protrocl import socket words ={'how are you?':'Fine ,thank you'} 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 ('Connected 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()
下一篇: Openlayers3加载天地图