这个想法是创建一个服务器来发送和接收备份文件,现在服务器从python客户端和另一个c++客户端接收1个msg,问题是,python客户端设法发送1个字符串,然后服务器有点看起来,我必须结束连接,这是对于python客户端,当我试图从c++客户端发送数据时,我什么也没有
我正在使用Websockets,但我的问题似乎是在尝试:语句,实在想不出我的问题在哪里
旁注:我正在使用quit()来停止我的程序,但是每次我使用它,我得到太多的错误,所以我不得不注释它
这是我的Server.py
代码import asyncio
import websockets
import socket
import sqlite3
import sys
def get_ip(): # returns primary private IP only
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
# doesn't even have to be reachable
s.connect(('10.255.255.255', 1))
IP = s.getsockname()[0]
except Exception:
IP = '127.0.0.1'
finally:
s.close()
return IP
async def handle_connectio(websocket, path): # recive and handle connection from client, would handle json or file data
while True:
try:
async for name in websocket:
#name = await websocket.recv()
print(f"<<< {name}")
#break
except websockets.exceptions.ConnectionClosed:
print (f"Coneecion terminada")
#quit()
break
else:
print (f"algo paso")
#quit()
break
print ("Iniciando el Server webSocket")
print ("Current Ip: " + get_ip())
servidor = websockets.serve(handle_connectio, get_ip(), 8000)
#loop = asyncio.get_event_loop()
#loop.run_until_complete(servidor)
asyncio.get_event_loop().run_until_complete(servidor)
asyncio.get_event_loop().run_forever()
#async def main(): # main function
# print ("Iniciando Server websocket")
# print("Current Ip: " + get_ip())
# async with websockets.serve(handle_connectio, get_ip(), 8000):
# await asyncio.Future()
#if __name__ == '__main__':
# asyncio.run(main())
编辑:我确实尝试简化我的代码,它设法接收msg并显示连接何时关闭-主要问题仍然存在。
async def handle_connectio(websocket, path): # recive and handle connection from client, would handle json or file data
try:
while True:
#async for data in websocket:
data = await websocket.recv()
print(f"<<< {data}")
await asyncio.sleep(1)
except websockets.exceptions.ConnectionClosed:
print (f"Coneecion terminada")
edit2:这是我的客户端代码,如果这不起作用,我将切换到套接字
import asyncio
import websockets
async def client():
direc = "ws://192.168.1.69:8000"
async with websockets.connect(direc) as web:
while True:
nombre = input("Introduce el mensaje >>> ")
await web.send(nombre)
asyncio.get_event_loop().run_until_complete(client())
查看并运行https://websockets.readthedocs.io/en/stable/上的示例代码,很明显,您的连接处理程序不应该永远循环(while True:
),而是在处理websocket提供的所有消息后退出。当另一条消息到达时,它将再次被调用。
编辑:
原始服务器代码工作正常。问题是客户端正在使用input()
功能,导致asyncio
无法正常运行,导致websocket
协议无法正常运行,导致消息无法发送。在发送(await asyncio.sleep(1)
)之后有一个小的延迟,尽管理想情况下input()
和asyncio
通信逻辑将被分开,以避免任意延迟。
Ok,由于一些奇怪的原因,websockets不能正常工作/行为,所以我不得不切换到Sockets,现在我可以来回发送数据,我会在未来为任何人发布我的客户端和服务器代码。
Server.py
import socket
# socket.SOCK_STREAM -> TCP
# socket.SOCK_DGRAM -> UDP
def get_ip(): # returns primary private IP only
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
# doesn't even have to be reachable
s.connect(('10.255.255.255', 1))
IP = s.getsockname()[0]
except Exception:
IP = '127.0.0.1'
finally:
s.close()
return IP
def servidor():
print (f"Iniciando el Servidor Sockets")
print (f"Current IP Addres: " + get_ip())
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((get_ip(), 8000))
server.listen(1)
conn, address = server.accept() # Accept the Client connection
while True:
#1024 is the bandwidth bits
try:
msg = conn.recv(1024).decode() # Recive the msg and trasform it from Binary to String
print("<<< " + msg)
except:
print (f"coneccion terminada")
break
if __name__ == "__main__":
servidor()
Client.py
import socket
print ('Iniciando cliente')
conn_client = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
conn_client.connect( ('192.168.1.68', 8000))
while True:
try:
msg = (f">>> ")
conn_client.sendall(msg.encode())
except:
print (f"Connection Close")
break
#recibido = conn_client.recv(1024)
#print (recibido.decode())
conn_client.close()