示例输出最终看起来像:
客户端:
输入新命令:B50
输入新命令H70
输入新命令:Z80
订阅方: 收到:B50
接受:H70
收到:Z80
当前发布商代码
#!/usr/bin/env python
import socket
TCP_IP = '127.0.0.1'
TCP_PORT = 5005
BUFFER_SIZE = 1024
def sendMsg(str):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((TCP_IP, TCP_PORT))
s.send(str.encode())
data = s.recv(BUFFER_SIZE)
s.close()
return
while 1:
MESSAGE = input("Enter Command: ")
sendMsg(MESSAGE)
print ("received data:", data.decode())
当前用户代码
#!/usr/bin/env python
import socket
TCP_IP = ''
TCP_PORT = 5005
BUFFER_SIZE = 20 # Normally 1024, but we want fast response
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((TCP_IP, TCP_PORT))
s.listen(1)
conn, addr = s.accept()
print ('Connection address:', addr)
while 1:
data = conn.recv(BUFFER_SIZE)
if not data: break
print ("received data:", data.decode())
conn.send(data) # echo
conn.close()
答案 0 :(得分:0)
想出来,必须将我的订阅者代码编辑到此
#!/usr/bin/env python
import socket
TCP_IP = ''
TCP_PORT = 5005
BUFFER_SIZE = 20 # Normally 1024, but we want fast response
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((TCP_IP, TCP_PORT))
s.listen(1)
conn, addr = s.accept()
print ('Connection address:', addr)
while 1:
data = conn.recv(BUFFER_SIZE)
if data:
print ("received data:", data.decode())
conn.send(data) # echo
s.listen(1)
conn, addr = s.accept()
conn.close()