python服务器已完成,但未侦听

2024-05-01 22:03:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经为我的一个项目创建了这个服务器,它完成时没有任何错误,但我希望它能够侦听传入的连接这里是代码

import socket
import sys
def socket_cr():
    try:
        global host
        global port
        global s
        host = ''
        port = 9999
        s= socket.socket()
    except socket.error as msg:
        print("socket creatin error " + (str(msg)))
socket_cr()
def socket_bind():
    try:
        global host
        global port
        global s
        print("binding to port :" + str(port))
        s.bind((host, port))
        s.listen(5)
    except socket.error as msg:
        print("Socket binding error" + str(msg) + "\n" + "retrying")
        socket_bind()
def socket_acept():
    conn, address = s.accept()
    print("connection has been astablished | " + "IP" + address[0] + "| port" + str(address[1]))
def send_command(conn):
    while True:
        cmd = input()
        if cmd == 'quite':
            conn.close()
            s.close()
            sys.exit()
        if len(str.encode(cmd)) > 0:
            conn.send(str.encode(cmd))
            client_response = str(conn.recv(1034), "utf-8")
            print(client_response, end="")
def main():
    socket_cr()
    socket_bind()
    socket_acept()
    main()

输出为:

Process finished with exit code 0

把它放在端口9999的绑定插座上


Tags: importcmdhostbindportaddressdefmsg
1条回答
网友
1楼 · 发布于 2024-05-01 22:03:19

你的代码有很多问题。如果你不介意的话,我将为你重写整个代码。 修订代码:

import socket
import sys

#No need to define functions for everything OR make the variables global every time.
try:
    HOST = ''
    PORT = 9999
    s = socket.socket()
except socket.error as msg:
    #You don't need to convert msg to a string since it's already a string. 
    print('Socket creating error '+ msg)

print('Binding to port: '+ str(PORT))
try:
    s.bind((HOST, PORT))
except socket.error as msg:
    print('Socket binding error '+msg+'\nRetrying.')
s.listen(5)
while True:
    conn, address = s.accept()
    # Address is not an iterable, you can't index elements in it. Address is the IP of the device you have just connected to.
    print('Connection has been established | IP '+ address)
    cmd = input()
    if cmd == 'quit':
        # You can end the connection with only a s.close()
        s.close()
        sys.exit()
        #encode is a method of a string, not a function.
        # Also, you have to specify how you want to encode the string e.g. mystring.encode('ascii')
        #Since it isn't specified, I'll assume it's ascii.
    if len(cmd.encode('ascii')) > 0:
        conn.send(cmd.encode('ascii'))
        # If the client is sending it encoded in ascii as well, instead of str(), you should decode it
        client_response = conn.recv(1034).decode('ascii')
        print(client_response, end='')

如您所见,为所有这些函数定义函数是不必要的,这会使代码变得不干净。现在,如果可能的话,应该在代码的开头定义变量。而且,您应该使主机0.0.0.0,以确保公共访问。 现在,记住,函数不应该被过度使用

很乐意帮忙

相关问题 更多 >