我的问题是:为什么我的客户没有收到来自我服务器的消息?我是否需要有线程客户端来发送和接收消息?
和其他许多人一样,我正在尝试进行UDP聊天。对于我的实现,我计划让用户通过服务器聊天。这意味着客户端将消息发送到服务器,服务器将其发送给连接到服务器的其他用户。为此,我在客户端实现了一个发送和接收线程。当我运行两个客户端和服务器时,我可以看到消息通过文本输出和wireshark流量发送到服务器。我还看到服务器尝试通过文本输出和wireshark将数据发送到其他客户端。我不是python 3的新手,但这是我第一次尝试socket编程和使用线程。
客户代码:
# Filename: client.py
# TODO list
# Implement commands
# States
# Version Check
import socket
import threading
import sys
# Version
VERSION = '1.0'
# Set variables
HOST, PORT = '127.0.0.1', 8888
BUFFER = 1024
def send():
while True:
msg = input('>>')
soc.sendto(msg.encode("ascii"), (HOST,PORT))
def receive():
while True:
data = soc.recvfrom(BUFFER)
print(data)
if __name__ == '__main__':
# Create socket
try:
soc = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
print("Client Socket Created")
except socket.error as e:
print("Failed to create socket. {}".format(e))
sys.exit(1)
pdu = input(">>")
# This works
thread_send = threading.Thread(target=send())
thread_send.start()
# but not this???
thread_receive = threading.Thread(target=receive())
thread_receive.start()
服务器代码: #Filename:server.py
import socket
import sys
# Version
VERSION = '1.0'
# Define global constants
HOST = 'localhost'
PORT = 8888
BUFFER = 1024
USERS = {'mkohn': 'abcd', 'wpolk': '1234'}
try:
# Create UDP/DGRAM Socket
soc = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
print("Server socket created")
except socket.error:
# Socket creation failed
print("Server Failed to create server socket.")
sys.exit(10)
try:
# Bind to a socket
soc.bind((HOST, PORT))
except socket.error:
# Bind failed
print("Server Bind failed")
sys.exit(11)
# Socket setup complete
print("socket bind complete")
def validate_user(uname, pw):
if USERS.get(uname) == pw:
return True
else:
return False
def parse_message(message):
pass
def connect_users(requestor, requestee):
pass
# Stores client logged into server
connected_clients = []
# Stores Chats
chats = []
while 1:
# Get address and data from client
data, addr = soc.recvfrom(BUFFER)
if addr not in connected_clients:
connected_clients.append(addr)
msg = data.decode('ascii')
print("Received from {}: Msg: {}".format( addr, msg ) )
if not data:
break
reply = "OK...{}".format(msg)
for client in connected_clients:
if client != addr:
print("Sending to: {}".format(client))
print(reply)
soc.sendto(reply.encode('ascii'), client)
soc.close()
client1输出(端口61417):
>>y you no work
>>bueller
>>cheese
>>my name is mike
client2输出(端口56778):
>>hi
>>what
>>where are you
服务器输出:
Received from ('127.0.0.1', 61417): Msg: y you no work
Sending to: ('127.0.0.1', 56778)
OK...y you no work
Received from ('127.0.0.1', 61417): Msg: bueller
Sending to: ('127.0.0.1', 56778)
OK...bueller
Received from ('127.0.0.1', 61417): Msg: cheese
Sending to: ('127.0.0.1', 56778)
OK...cheese
Received from ('127.0.0.1', 61417): Msg: my name is mike
Sending to: ('127.0.0.1', 56778)
OK...my name is mike
Received from ('127.0.0.1', 56778): Msg: hi
Sending to: ('127.0.0.1', 61417)
OK...hi
Received from ('127.0.0.1', 56778): Msg: what
Sending to: ('127.0.0.1', 61417)
OK...what
Received from ('127.0.0.1', 56778): Msg: where are you
Sending to: ('127.0.0.1', 61417)
OK...where are you
-------------------------- UPDATE -------------------- -------------
问题出在我的线程上。只需要传递参考。
正确的:
thread_send = threading.Thread(target=send)
不正确的:
thread_send = threading.Thread(target=send())