import socket, sys
def create_socket(): # Creates a socket which connects two or more computers together
host = ""
port = 9999
socket_ = socket.socket()
try:
host
port
socket_
except socket.error as msg:
print("Socket Creation Error: " + str(msg))
return host, port, socket_
def bind_Socket(): # Binds the Socket and listening for connections
host, port, socket_ = create_socket()
try:
host
port
socket_
print("Binding the Socket: " + str(port))
socket_.bind((host, port))
socket_.listen(5)
except socket.error as msg:
print("Socket Creation Error: " + str(msg) + "Retrying....")
bind_Socket()
return host, port, socket_
def socket_accept(): # Establishes a connection with a client (socket must be listening)
host, port, socket_ = bind_Socket()
conn, address = socket_.accept()
send_command(conn)
print("Connection successful... " + "IP: " + address[0] + "\n" + "Port: " + address[1])
def send_command(conn): # Sends command to client
host, port, socket_ = bind_Socket()
cmd = ""
while (cmd != "Quit"):
cmd = input("Enter a command: ")
if(len(str.encode(cmd)) > 0):
conn.send(str.encode(cmd))
client_response = str(conn.recv(1024,"UTF-8"))
print(client_response, end="")
else:
conn.close()
socket_.close()
sys.exit()
def main():
create_socket()
bind_Socket()
socket_accept()
main()
问题是,当我在main()
中调用bind_Socket()
时,它将打印两次“绑定套接字:9999”,因为它也在函数socket_accept()
中被调用。我只想知道如何使用在一个函数中声明的相同变量,并在另一个函数中实现它,而不必像我那样使用全局变量或调用函数
函数可以返回其他函数用作参数的对象
按如下方式设置主屏幕:
然后更新
_accept
以接受参数:从而将套接字对象传递给accept方法
相关问题 更多 >
编程相关推荐