Python - 套接字通信,多条消息

时间:2016-06-12 17:39:56

标签: python sockets communication

嘿伙计们,我想我再次需要你的帮助:(

我坚持这个套接字通信,我到处都看,但我还没有找到答案。

问题:我只能在客户端发出错误或结束脚本之前从客户端发送1条消息。 我需要能够向服务器发送多条消息。

服务器端(如下所示)应该没问题:

# Echo server program
import socket
import time
import os

#-----------------------------------------------------------------------------------------------------------------------

today = time.strftime('%Y.%m.%d')
logFileName = "log - " + today + ".txt"


HOST = '10.0.0.16'                                                          
PORT = 8080                                                                 # Reserve a port for your service
BUFFER_SIZE = 1024                                                          
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)                       # Create a socket object
s.bind((HOST, PORT))                                                        # Bind to the port


def print_write(text):
    log.write(time.strftime("%H:%M:%S") + "  |  " + text)
    log.write("\n")
    print text


#-----------------------------------------------------------------------------------------------------------------------


if os.path.isfile(logFileName) is True:
    log = open(logFileName, 'a+')
    print_write("[SERVER] Log for " + today + " already exists.")
    print_write("[SERVER] Starting comms")
else:
    print "[SERVER] Log doesn't exist"
    log = open(logFileName, 'a+')                                           # Create file -> log - %date%.txt
    print_write("[SERVER] Log created")


while True:
    s.listen(1)
    conn, addr = s.accept()
    data = conn.recv(BUFFER_SIZE)
    if data == "Comms Shutdown":
        print_write("------ REMOTE SHUTDOWN ------")
        conn.close()
        raise SystemExit
    else:
        print_write("[COMMS] " + str(addr) + " says: " + data)

log.close()

对不起,如果它非常混乱和令人困惑,但我没有太多时间来完成这个项目,如果你有任何问题只是问。

对于客户端我没有太多但是在这里,我会给你这个:

import socket

HOST = '10.0.0.16'          # The remote host
PORT = 8080                 # The same port as used by the server
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))

while True:
    msg = raw_input()
    s.sendall(msg)
    print msg

我知道它不起作用,它只是让你知道我需要什么。

提前谢谢。

1 个答案:

答案 0 :(得分:4)

问题是,您只能从每个打开的连接中读取第一条消息,然后再转到下一条消息。 accept()方法等待新连接,并为您提供新的连接所需的信息。另一方面,recv()方法从现有连接接收数据,如果没有,则等待。如果要从单个客户端接收多条消息,可以等待第一次连接,然后等待recv()的数据。这看起来像这样:

s.listen(1)
conn, addr = s.accept()
while True:
    data = conn.recv(BUFFER_SIZE)
    if data == "Comms Shutdown":
        print_write("------ REMOTE SHUTDOWN ------")
        conn.close()
        raise SystemExit
    else:
        print_write("[COMMS] " + str(addr) + " says: " + data)

如果您还希望能够管理多个客户端,则必须从等待新连接的while循环为每个客户端创建一个线程。这有点复杂:

def client_handler(conn):
    while True:
        data = conn.recv(BUFFER_SIZE)
        if data == "Comms Shutdown":
            print_write("------ REMOTE SHUTDOWN ------")
            conn.close()
            raise SystemExit  
            # this will kill the server (remove the line above if you don't want that)
        else:
             print_write("[COMMS] " + str(addr) + " says: " + data)

while True:
    s.listen(1)
    conn, addr = s.accept()
    recv_thread = threading.Thread(target=client_handler, args=(conn, ))
    recv_thread.start()

所有这些代码都是未经测试的。请注意,我省略了日志记录部分和套接字创建部分以及所有导入。