在套接字服务器运行时运行单独的代码? [英] Running separate code while a socket server is running?

查看:30
本文介绍了在套接字服务器运行时运行单独的代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何让套接字服务器运行以接受传入连接并处理该部分代码,同时又不让代码等待卡在同一循环中的新连接?

How can I have a socket server running that accepts incoming connections and deals with that part of the code, while not having code waiting for new connections stuck in that same loop?

我刚刚开始尝试学习.TCP 处理程序会有用吗?

I am just starting trying to learn. Would a TCP Handler be useful?

我只需要一些有关此主题的简单示例.我想要一些东西,比如在服务器中有一个命令部分.所以我可以在服务器运行时做一些事情.

I just need some simple examples on this topic. I'm wanting something like having a commands portion in the server. So i can do certain things while the server is running.

我正在尝试做的事情:

1 - TCP server for multiple clients
2 - Respond to more than one at a time when needed
3 - Text input availability at all time, to be used for getting/setting info
4 - A simple way to get/save client address info. Currently using a list to save them. 

推荐答案

Python 在 asyncore 模块(http://docs.python.org/library/asyncore.html).

Python has builtin support of asynchronous socket handling in asyncore module (http://docs.python.org/library/asyncore.html).

异步套接字处理意味着您必须在您的代码(主循环)中至少执行一次套接字处理循环迭代:

Asynchronous socket handling means that You have to execute at least one iteration of socket processing loop inside Your code (main loop):

asyncore.loop(count=1)

从文档中获取的示例:

import asyncore
import socket

class EchoHandler(asyncore.dispatcher_with_send):

    def handle_read(self):
        data = self.recv(8192)
        if data:
            self.send(data)

class EchoServer(asyncore.dispatcher):

    def __init__(self, host, port):
        asyncore.dispatcher.__init__(self)
        self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
        self.set_reuse_addr()
        self.bind((host, port))
        self.listen(5)

    def handle_accept(self):
        pair = self.accept()
        if pair is None:
            pass
        else:
            sock, addr = pair
            print 'Incoming connection from %s' % repr(addr)
            handler = EchoHandler(sock)

server = EchoServer('localhost', 8080)
# Note that here loop is infinite (count is not given)
asyncore.loop()

每次套接字接受连接时,循环都会调用handle_accept.每次可以从套接字读取数据时,都会调用 handle_read,依此类推.

Each time the socket accepts the connection handle_accept is called by the loop. Each time the data is available to read from socket handle_read is called and so on.

您可以通过这种方式使用 TCP 和 UDP 套接字.

You can use both TCP and UDP sockets in this manner.

这篇关于在套接字服务器运行时运行单独的代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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