python 客户端和服务器套接字编程在单个脚本中
Posted
技术标签:
【中文标题】python 客户端和服务器套接字编程在单个脚本中【英文标题】:python client and server socket programming in a single script 【发布时间】:2021-11-30 21:45:08 【问题描述】:我必须将客户端脚本和服务器脚本组合在一个脚本中,并从同一个文件本身运行客户端和服务器。 我可以分别创建两者,但无法在 sibgle 脚本中创建两者。请有人帮助我,过去两天我都陷入了困境。
我已经尝试过这段代码(取自堆栈溢出),但它在我的机器上不起作用。
有人请帮忙!!!
还请让我知道msg!r
中的!r
是做什么的?
我正在使用 python 3.9.6
import asyncio
async def echo_client(msg):
reader, writer = await asyncio.open_connection('127.0.0.1',5050)
print(f'Send:msg!r')
writer.write(msg.encode())
await writer.drain()
data = await reader.read(100)
print(f'Recieved: data.decode()!r')
print('close the connection')
writer.close()
await writer.wait_closed()
async def handle_echo(reader, writer):
data = await reader.read(100)
message = data.decode()
addr = writer.get_extra_info('peername')
print(f'Recieved message!r from addr!r')
print(f'Send:message!r')
writer.write(data)
await writer.drain()
print('close the connection')
writer.close()
async def main():
server = await asyncio.start_server(handle_echo,'127.0.0.1',5050)
addr = server.sockets[0].getsockname()
print(f'Serving on addr')
async with server:
await server.serve_forever()
# asyncio.run(echo_client("hello server"))
asyncio.run(main())
【问题讨论】:
【参考方案1】:**这似乎工作** 请查看并发表您的建议
import socket, threading
from time import sleep
host_ip = socket.gethostbyname("www.python.org")
port = 5051
print("host is ", host_ip)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print("socket successfully created")
s.bind(('', port))
print("socket bind to %s" % (port))
s.listen(5)
print("socket is listening")
def server_func():
while True:
c, addr = s.accept()
print("got connection from", addr)
c.send("[SERVER]: Thank you for connecting\n".encode())
c.send("[SERVER]: This is your server sending the message\n\n".encode())
print(c.recv(1024).decode())
break
def client_func():
s2 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s2.connect(("localhost", port))
print("\n")
print(s2.recv(1024).decode())
print(s2.recv(1024).decode())
s2.send("[CLIENT]: *****Hello Server, This is client*****".encode())
if __name__ == '__main__':
t1 = threading.Thread(target=server_func)
t1.start()
sleep(1)
t2 = threading.Thread(target=client_func)
t2.start()
【讨论】:
您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center。以上是关于python 客户端和服务器套接字编程在单个脚本中的主要内容,如果未能解决你的问题,请参考以下文章