我必须制作一个简单的udp echo客户端和服务器,目前我的问题是客户端在代码"data,address=sock.recvfrom(dataSize(";。这是我的客户端和服务器代码(我删除了一些api函数,所以它不长(。我尝试了相同的端口和不同的端口,ip也一样,但我没有收到任何回复。我尝试了一个朋友的原始文件,他的版本有效,我在两个文件上都有相同的端口和ip以及相同的方法,但它仍然挂在第一行的echoClient方法receiveMSG上。
echoServerUDP.py
0<0# : ^
'''
@echo off
python "%~f0" %*
pause
exit /b 0
'''
#!/usr/bin/env python
import socket
import json
host = '0.0.0.0'
sport = 11111 # own port
dataSize = 1024
ip_adresses = {}
def echo_server():
receiveSock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
receiveSock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
receiveSock.bind((host,sport))
print("Starting up echo server on %s port %s" % (host, sport))
while True:
print("Waiting to receive message")
print("Generate a Session ...")
data, address = receiveSock.recvfrom(dataSize)
data = data.decode("utf-8")
if data:
print("receive data: %s from %s" % (data,address))
json_object = json.loads(data)
operation=json_object["operation"]
if operation == "register":
register(json_object["name"],json_object["value"],json_object["sid"])
json_message={"ergebnis":"ok"}
dump = json.dumps(json_message)
sendMSG(bytes(dump,encoding="utf-8"),address)
print("er")
if operation == "unregister":
unregister(json_object["name"],json_object["sid"])
if operation == "query":
query(json_object["sid"])
if operation == "reset":
reset(json_object["sid"])
print("sent %s bytes back to %s" % (data,address))
def sendMSG(data,address):
sendSock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sendSock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sendSock.sendto(data,address)
sendSock.close()
if __name__ == '__main__':
echo_server()
这里是echoClientUDP.py
0<0# : ^
'''
@echo off
python "%~f0" %*
pause
exit /b 0
'''
#!/usr/bin/env python
import socket
import time
import json
from random import randint
host = '127.0.0.1'
sport = 11111
dataSize = 1024
sid= randint(1,10000)
name=socket.gethostname()
own_ip = socket.gethostbyname(name)
def echo_client():
sendSock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
json_message = {"operation":"register","name":name,"value":own_ip,"sid":sid}
dump = json.dumps(json_message)
print("Sending %s to %s:%s" % (dump,host,sport))
sendMSG(sendSock, dump)
data = receiveMSG(sendSock)
if data:
print("Received: %s" % data)
except Exception as err:
print("Socket error: %s" %str(err))
finally:
print("Closing connection to the server")
sendSock.close()
def sendMSG(sendSock, data):
sendSock.connect((host, sport))
sendSock.sendall(bytes(data,encoding="utf-8"))
def receiveMSG(sock):
data, address = sock.recvfrom(dataSize)
print(data)
return data
if __name__ == '__main__':
echo_client()
请在某些方面付出更多的努力,比如你没有添加任何标题,你变得更复杂了。我也创建了一个类似的工作脚本。查看并观察该脚本,并对你的脚本进行更改
client.py:-
import socket
import sys
HEADER = 64
PORT = 65432
FORMAT = 'utf-8'
DISCONNECT_MESSAGE = "!DISCONNECT"
SERVER = socket.gethostbyname(socket.gethostname())
ADDR = (SERVER, PORT)
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(ADDR)
def send(msg):
message = msg.encode(FORMAT)
msg_length = len(message)
send_length = str(msg_length).encode(FORMAT)
send_length += b' ' * (HEADER - len(send_length))
client.send(send_length)
client.send(message)
print(client.recv(2048).decode(FORMAT))
def chat():
while True:
try:
a = input()
if 'quit' in a:
sys.exit()
else:
send(a)
except Exception as e:
print(e)
sys.exit()
chat()
server.py:-
import socket
import threading
HEADER = 64
PORT = 65432
SERVER = socket.gethostbyname(socket.gethostname())
ADDR = (SERVER, PORT)
FORMAT = 'utf-8'
DISCONNECT_MESSAGE = "Bye"
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(ADDR)
def handle_client(conn, addr):
print(f"[NEW CONNECTION] {addr} connected.")
connected = True
while connected:
msg_length = conn.recv(HEADER).decode(FORMAT)
if msg_length:
msg_length = int(msg_length)
msg = conn.recv(msg_length).decode(FORMAT)
if msg == DISCONNECT_MESSAGE:
connected = False
print(f"[{addr}] left")
print(f"[{addr}] {msg}")
conn.send("Msg received".encode(FORMAT))
conn.close()
def start():
server.listen()
print(f"[LISTENING] Server is listening on {SERVER}")
while True:
conn, addr = server.accept()
thread = threading.Thread(target=handle_client, args=(conn, addr))
thread.start()
print(f"[ACTIVE CONNECTIONS] {threading.activeCount() - 1}")
print("[STARTING] server is starting...")
start()
我在这里使用了线程来加快进程。
首先在后台运行server.py,然后运行client.py连接到服务器。