#python
Вопрос:
Я создавал простой чат на python, и у меня возникли проблемы с его запуском за пределами IDE, код работает, но не тогда, когда я экспортирую несколько сценариев, которые у меня есть, в виде .exe-это те сценарии, которые у меня есть server.py client.py и main.py main просто импортирует клиент, потому что он отклоняет компьютер, если я по какой-то причине попытаюсь запустить его с одного клиента. Я попытался встроить сценарии друг в друга, но сервер не позволяет запускать внутри него что-либо еще, и я не знаю, будет ли это работать внутри клиента. То, что я пытаюсь сделать, — это сделать так, чтобы он работал и работал для кого-то, кому я только что передал программу, без того, чтобы им пришлось проходить все шаги, которые запускаются server.py затем откройте main.py Сервер отлично работает как exe, но основной и клиент просто открываются и закрываются немедленно. И моя цель состоит в том, чтобы он работал полностью как файл .bat или исполняемый файл на основе консоли.
Вот как будет выглядеть программа при открытии. [Начальный экран main/client.py][1] [1]: https://i.stack.imgur.com/3PIey.png
вот это server.py сценарий (я изменил номера портов и, например, пример)
import socket
from threading import Thread
import subprocess
# server's IP address
SERVER_HOST = "1.2.3.4"
SERVER_PORT = 0000 # port
separator_token = "<SEP>" # separate client name and message
# initialize list/set of all connected client's sockets
client_sockets = set()
# create a TCP socket
s = socket.socket()
# make the port as reusable port
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
# bind the socket to the address we specified
s.bind((SERVER_HOST, SERVER_PORT))
# listen for upcoming connections
s.listen(5)
print(f"[*] Listening as {SERVER_HOST}:{SERVER_PORT}")
def listen_for_client(cs):
"""
This function keep listening for a message from `cs` socket
Whenever a message is received, broadcast it to all other connected clients
"""
while True:
try:
# keep listening for a message from `cs` socket
msg = cs.recv(0000).decode()
except Exception as e:
# client no longer connected
# remove it from the set
print(f"[!] Error: {e}")
client_sockets.remove(cs)
else:
# if we received a message, replace the <SEP>
# token with ": " for nice printing
msg = msg.replace(separator_token, ": ")
# iterate over all connected sockets
for client_socket in client_sockets:
# and send the message
client_socket.send(msg.encode())
while True:
# we keep listening for new connections all the time
client_socket, client_address = s.accept()
print(f"[ ] {client_address} connected.")
# add the new connected client to connected sockets
client_sockets.add(client_socket)
# start a new thread that listens for each client's messages
t = Thread(target=listen_for_client, args=(client_socket,))
# make the thread daemon so it ends whenever the main thread ends
t.daemon = True
# start the thread
t.start()
# close client sockets
for cs in client_sockets:
cs.close()
# close server socket
s.close()
и вот client.py (снова изменились номера и порты)
import socket
import random
from pyfiglet import figlet_format
from threading import Thread
from datetime import datetime
from colorama import Fore, init, Back
# initiate colours
init()
# available colours
colors = [Fore.BLUE, Fore.CYAN, Fore.GREEN, Fore.LIGHTBLACK_EX,
Fore.LIGHTBLUE_EX, Fore.LIGHTCYAN_EX, Fore.LIGHTGREEN_EX,
Fore.LIGHTMAGENTA_EX, Fore.LIGHTRED_EX, Fore.LIGHTWHITE_EX,
Fore.LIGHTYELLOW_EX, Fore.MAGENTA, Fore.RED, Fore.WHITE, Fore.YELLOW
]
client_color = random.choice(colors)
SERVER_HOST = "127.2.3.4"
SERVER_PORT = 0000 # server's port
separator_token = "<SEP>" # separates client name and message
# initialize TCP socket
s = socket.socket()
print(f"[*] Connecting to {SERVER_HOST}:{SERVER_PORT}...")
# connect to the server
s.connect((SERVER_HOST, SERVER_PORT))
print(figlet_format('M o n t y', font='colossal', justify='center') figlet_format('C R', font='alligator2', justify='center'))
print("[ ] Connected.")
print("Type and enter 'q' to exit the program any time")
# prompt the client for a name
name = input("Enter your name: ")
def listen_for_messages():
while True:
message = s.recv(0000).decode()
print("n" message)
# make a thread that listens for messages to this client amp; print them
t = Thread(target=listen_for_messages)
# make the thread daemon so it ends whenever the main thread ends
t.daemon = True
# start the thread
t.start()
while True:
# input message we want to send to the server
to_send = input()
# a way to exit the program
if to_send.lower() == 'q':
break
# add the datetime, name amp; the color of the sender
date_now = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
to_send = f"{client_color}[{date_now}] {name}{separator_token}{to_send}{Fore.RESET}"
# finally, send the message
s.send(to_send.encode())
# close the socket
s.close()
Заранее спасибо.