简体   繁体   English

使用python和套接字进行网络通信

[英]network communication using python and socket

I have succesfully made a code which starts a server which can be connected by other devices on my LAN with the CMD command telnet hostname port when the new "client" enters a word and presses enter the word is then sent back to them through the server. 我成功编写了一个代码,启动了一个服务器,当新的“客户端”输入一个单词并按下输入的单词,然后通过服务器发送回给他们时,该服务器可以通过CMD命令telnet hostname port连接到我的LAN上的其他设备。 。 My question is if i connected 2 devices to the server how would i get the message to get sent from one to the server then back to the other. 我的问题是,如果我将2台设备连接到服务器,我如何将消息从一台发送到服务器,然后又发送回另一台。 Like a messaging programme. 就像一个消息传递程序。 The code i have used is shown below 我使用的代码如下所示

import socket
import sys
from _thread import *

host = ''
port = 5555
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

try:
    s.bind((host, port))
except socket.error as e:
    print(str(e))

s.listen(5)
print('Waiting for a connection.')

def threaded_client(conn):
    conn.send(str.encode('Welcome, type your info\n'))
    final_char = ""

    while True:
        data = conn.recv(2048)
        char = data.decode("utf-8")
        print(data)
        if data != b'\r\n':
            final_char += char
            print(final_char)
        else:


            reply = 'Server output: '+ final_char+"\n"
            if not data:
                break
            conn.sendall(str.encode(reply))
            final_char = ""
    conn.close()



while True:

    conn, addr = s.accept()
    print(addr)
    print(conn)
    print('connected to: '+addr[0]+':'+str(addr[1]))

    start_new_thread(threaded_client,(conn,))

Not an actual implementation, but some theory: 不是实际的实现,而是一些理论:

You need to keep a list of all the clients you have an active connection to: 您需要保留与以下设备建立活动连接的所有客户端的列表:

while ( true )

    client = server.accept()

    clientList.add(client)

    startThread(client)

Then in the thread 然后在线程中

while ( true )

    data = connection.receive()

    for client in clientList

        client.sendall( data )

Take a look at ZQM the python library works perfect and it has already implemented what you need using sockets internally. 看一下ZQM,python库可以完美地工作,它已经在内部使用套接字实现了您所需要的。 https://learning-0mq-with-pyzmq.readthedocs.io/en/latest/ https://learning-0mq-with-pyzmq.readthedocs.io/en/latest/

Take a look at their publisher / subscriber message pattern. 看一下他们的发布者/订阅者消息模式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM