在套接字服务器运行时运行单独的代码?

发布于 2024-12-05 01:10:59 字数 448 浏览 0 评论 0原文

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

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

我只需要一些关于这个主题的简单例子。我想要在服务器中拥有命令部分之类的东西。所以我可以在服务器运行时做某些事情。

编辑:我想做的事情:

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. 

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?

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.

EDIT: What I'm trying to do:

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. 

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

沉鱼一梦 2024-12-12 01:10:59

您可以在 线程 中运行套接字服务器。

import threading
import SocketServer

server = SocketServer.TCPServer(('localhost', 0), SocketServer.BaseRequestHandler)
th = threading.Thread(target=server.serve_forever)
th.daemon = True
th.start()

You can run your socket server in a thread.

import threading
import SocketServer

server = SocketServer.TCPServer(('localhost', 0), SocketServer.BaseRequestHandler)
th = threading.Thread(target=server.serve_forever)
th.daemon = True
th.start()
心不设防 2024-12-12 01:10:59

Python 在 asyncore 模块中内置了对异步套接字处理的支持 (http:// /docs.python.org/library/asyncore.html)。

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

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,依此类推。

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

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)

Example taken from documentation:

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

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.

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

兰花执着 2024-12-12 01:10:59

我不太确定你在问什么,但通常在服务器端,你会调用socket()、bind()和listen()来设置套接字,然后循环调用accept()。此accept() 调用将阻塞,直到建立客户端连接。

对于简单的服务器,您可以处理客户端在循环内发出的任何请求。对于现实世界的服务器,您需要生成一些其他机制(例如,新的线程或进程,具体取决于语言/平台)来异步处理请求,以便原始循环可以在accept()调用上再次迭代并继续回到监听连接。

有关 Python 中的更多信息和示例,请参阅 Python 套接字文档:

http://docs.python.org/ howto/sockets.html

I'm not exactly sure what you are asking, but normally on the server side, you make socket(), bind() and listen() calls to setup the socket, and then loop around an accept() call. This accept() call blocks until a client connection is made.

For simple servers, you handle whatever request the client makes within the loop. For real-world servers, you need to spawn some other mechanism (e.g. a new thread or process, depending on the language/platform) to handle the request asynchronously, so that the original loop can iterate again on the accept() call and go back to listening for connections.

See the Python socket doc for more info and examples in Python:

http://docs.python.org/howto/sockets.html

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文