python服务器完成但不监听

时间:2018-08-11 04:57:36

标签: python server

我已经为我的一个项目创建了此服务器,并且没有任何错误,但是我希望它监听传入的连接,这是代码

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()

,输出为:

  

以退出代码0结束的过程

将其绑定到端口9999

1 个答案:

答案 0 :(得分:1)

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

console.log(String(req.file.buffer))

如您所见,为所有函数定义函数都是不必要的,这会使代码变得不整洁。现在,如果可能,您应该在代码的开头定义变量。并且,您应该使主机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='') 可以确保公众可见。 现在,请记住,不应过度使用这些功能。

很乐意提供帮助。