【发布时间】:2016-10-13 03:10:40
【问题描述】:
我被这个套接字通信卡住了,我到处找了,但我还没有找到答案。
问题:在给我一个错误或结束脚本之前,我只能从客户端发送 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
我知道这行不通,只是为了让您了解我需要什么。
提前谢谢你。
【问题讨论】:
-
你的服务器代码在再次循环之前只调用了一次recv,你应该使用while循环或类似的东西在打开新连接之前多次调用
recv..
标签: python sockets communication