我正在尝试创建一个对等消息应用程序,我了解我需要该应用程序的每个实例既是服务器又是客户端,就像下面的代码一样,但是我想知道如何设置在端口上,我可以在同一端口上发送和接收消息吗?
下面的代码是该应用程序的一个实例,我可以与另一个版本进行通信,但是我必须设置另一个版本以在端口9000上发送消息并在6190上接收消息。这将无法正常工作。第三个用户连接?
当前情况: 用户1:在9000上接收,在6190上发送 用户2:在6190上接收,在9000上发送
import socket
import time
import threading
global incoming
def server_socket(): #call server_socket() in build method?
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('', 9000))
s.listen(1)
host_name = socket.gethostname()
ip_address = socket.gethostbyname(host_name)
print("IP address is: ", ip_address)
except socket.error as e:
print("Socket Error !!", "Unable To Setup Local Socket. Port In Use")
while True:
conn, addr = s.accept()
incoming_ip = str(addr[0])
data = conn.recv(4096)
data = data.decode('utf-8')
print("message recieved is: ", data)
conn.close()
s.close()
def client_send_message():
message = "Hello World"
message = message.encode('utf-8')
c = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
c.connect(("127.0.0.1", 6190))
except Exception as e:
print("Connection Refused", "The Address You Are Trying To Reach Is Currently Unavailable")
try:
c.send(message)
except Exception as e:
print(e)
c.close()
t = threading.Thread(target=server_socket)
t.start()
for i in range(5):
time.sleep(30)
client_send_message()