Python套接字-使套接字保持活动状态吗? [英] Python sockets - keep socket alive?

查看:106
本文介绍了Python套接字-使套接字保持活动状态吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用Python套接字时遇到了一些麻烦.只要有人连接,它就可以正常工作,但是如果他们断开连接,则服务器程序将关闭.我希望服务器程序在客户端关闭后保持打开状态.我正在使用一会儿True循环来使连接保持活动状态,但是一旦客户端关闭连接,服务器就会关闭其连接.

I'm having a little trouble with sockets in Python. Whenever someone connects it works fine but if they disconnect the server program closes. I want the server program to remain open after the client closes. I'm using a while True loop to keep the connection alive but once the client closes the connection the server closes it's connection.

这是客户:

import socket, sys
conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = sys.argv[1]
port = int(sys.argv[2])
conn.connect((host, port))

print("Connected to host " + sys.argv[1])
td = 1
while td == 1:
   msg = raw_input('MSG:  ')

这是服务器:

import socket, sys

socket.setdefaulttimeout(150)
host = ''               
port = 50005
socksize = 1024

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host, port))
print("Server started on port: %s" % port)
s.listen(1)
print("Now listening...\n")
conn, addr = s.accept()

while True:
    print 'New connection from %s:%d' % (addr[0], addr[1])
    data = conn.recv(socksize)
    if not data:
        break
    elif data == 'killsrv':
        conn.close()
        sys.exit()
    else:
       print(data)

推荐答案

如果客户端关闭连接,则希望它关闭套接字.

If a client closes a connection, you want it to close the socket.

似乎这里有些脱节,我将尝试详细说明.创建套接字,绑定和侦听时,您已经为他人打开了大门,并与您建立连接.

It seems like there's a bit of a disconnect here that I'll try to elaborate on. When you create a socket, bind, and listen, you've established an open door for others to come and make connections to you.

一旦客户端连接到您,您就可以使用accept()调用接受连接并获得一个新的套接字(conn),该套接字将返回给您以便与客户端进行交互.您原来的侦听套接字仍在那里并处于活动状态,您仍然可以使用它来接受更多新连接.

Once a client connects to you, and you use the accept() call to accept the connection and get a new socket (conn), which is returned for you to interact with the client. Your original listening socket is still there and active, and you can still use it to accept more new connections.

查看您的代码,您可能想要执行以下操作:

Looking at your code, you probably want to do something like this:

while True:
    print("Now listening...\n")
    conn, addr = s.accept()

    print 'New connection from %s:%d' % (addr[0], addr[1])
    data = conn.recv(socksize)
    if not data:
        break
    elif data == 'killsrv':
        conn.close()
        sys.exit()
    else:
        print(data)

请注意,这只是一个起点,正如其他人所建议的那样,您可能希望使用select()以及分叉进程或生成线程来为每个客户端提供服务.

Please note that this is just a starting point, and as others have suggested you probably want to use select() along with forking off processes or spawning threads to service each client.

这篇关于Python套接字-使套接字保持活动状态吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆