服务器在收到 1 条消息后停止接收消息
server stop receiving msg after 1 msg receive
想法是创建一个用于发送和接收备份文件的服务器,现在服务器从 python 的客户端和另一个 C++ 的客户端接收 1 条消息,问题是 python 客户端设法发送 1 个字符串,然后服务器看起来有点像,我必须结束连接,这是针对 python 客户端的,当我尝试从 C++ 客户端发送数据时,我什么也没得到
我正在使用 Websockets,但我的问题似乎出在 try: 语句上,老实说我无法弄清楚我的问题在哪里
旁注:我正在使用 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())
编辑: 我确实尝试简化我的代码,它设法接收消息并在连接关闭时显示 - 主要问题仍然存在。
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:
),而是在处理完所有提供的消息后退出通过网络套接字。当另一条消息到达时将再次调用它。
编辑:
原始服务器代码工作正常。问题是客户端正在使用 input()
函数,它从 运行 阻止 asyncio
,从而阻止 websocket
协议从 运行 正确地阻止消息发送.发送 (await asyncio.sleep(1)
) 后的一个小延迟起作用,尽管理想情况下 input()
和 asyncio
通信逻辑将分开,以避免任意延迟。
好吧,由于某些奇怪的原因,websockets 不会 work/behave 正确,所以我不得不切换到套接字,现在我可以来回发送数据,我会 post 我的客户端和服务器代码供任何人使用关于未来。
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()
想法是创建一个用于发送和接收备份文件的服务器,现在服务器从 python 的客户端和另一个 C++ 的客户端接收 1 条消息,问题是 python 客户端设法发送 1 个字符串,然后服务器看起来有点像,我必须结束连接,这是针对 python 客户端的,当我尝试从 C++ 客户端发送数据时,我什么也没得到
我正在使用 Websockets,但我的问题似乎出在 try: 语句上,老实说我无法弄清楚我的问题在哪里
旁注:我正在使用 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())
编辑: 我确实尝试简化我的代码,它设法接收消息并在连接关闭时显示 - 主要问题仍然存在。
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:
),而是在处理完所有提供的消息后退出通过网络套接字。当另一条消息到达时将再次调用它。
编辑:
原始服务器代码工作正常。问题是客户端正在使用 input()
函数,它从 运行 阻止 asyncio
,从而阻止 websocket
协议从 运行 正确地阻止消息发送.发送 (await asyncio.sleep(1)
) 后的一个小延迟起作用,尽管理想情况下 input()
和 asyncio
通信逻辑将分开,以避免任意延迟。
好吧,由于某些奇怪的原因,websockets 不会 work/behave 正确,所以我不得不切换到套接字,现在我可以来回发送数据,我会 post 我的客户端和服务器代码供任何人使用关于未来。
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()