我已经建立了客户端 - 服务器通信。
问题在于我无法发送多封邮件,我试图修复它,而我也不知道错误。
这是我的代码:
**服务器代码和客户端代码在两个不同的python窗口中运行。
服务器:
import socket
s = socket.socket() # Create a socket object
host = socket.gethostname() # Get local machine name
port = 12345 # Reserve a port for your service.
s = socket.socket()
s.bind((host, port)) # Bind to the port
s.listen(5) # Now wait for client connection.
conn, addr = s.accept()
print('Got connection from ', addr[0], '(', addr[1], ')')
while True:
data = conn.recv(1024)
print(data.decode("utf-8"))
if not data:
break
conn.sendall(data)
conn.close()
print('Thank you for connecting')
客户端:
import socket # Import socket module
host = socket.gethostname() # Get local machine name
port = 12345 # Reserve a port for your service.
conn = socket.socket() # Create a socket object
conn.connect((host, port))
conn.sendall(b'Connected. Wait for data...')
intosend = input("message to send:")
conn.sendall(bytes(intosend, 'utf-8'))
data = conn.recv(1024)
intosend= "no"
while intosend != "quit":
intosend = input("message to send:")
conn.sendall(bytes(intosend, 'utf-8'))
conn.close() # Close the socket when done
print(data.decode("utf-8"))
有人可以帮忙吗?
答案 0 :(得分:2)
服务器端添加了一点保护。也许这就是你需要的?客户端进程完成后,服务器将继续侦听连接。通过启动服务器,启动客户端,发送消息,再次启动客户端并发送另一条消息来尝试...
import socket
import threading
import sys
s = socket.socket() # Create a socket object
host = socket.gethostname() # Get local machine name
port = 12345 # Reserve a port for your service.
s = socket.socket()
s.bind((host, port)) # Bind to the port
s.listen(5) # Now wait for client connection.
def processMessages(conn, addr):
while True:
try:
data = conn.recv(1024)
if not data:
conn.close()
print(data.decode("utf-8"))
conn.sendall(bytes('Thank you for connecting', 'utf-8'))
except:
conn.close()
print("Connection closed by", addr)
# Quit the thread.
sys.exit()
while True:
# Wait for connections
conn, addr = s.accept()
print('Got connection from ', addr[0], '(', addr[1], ')')
# Listen for messages on this connection
listener = threading.Thread(target=processMessages, args=(conn, addr))
listener.start()
答案 1 :(得分:1)
您需要在客户端循环接受输入并发送它的代码。
此代码在客户端为我工作。
import socket # Import socket module
host = socket.gethostname() # Get local machine name
port = 12345 # Reserve a port for your service.
conn = socket.socket() # Create a socket object
conn.connect((host, port))
conn.sendall(b'Connected. Wait for data...')
while 1:
intosend = input("message to send:")
conn.sendall(intosend.encode('utf-8'))
#data received back from sever
data = conn.recv(1024)
print("Data: ", data.decode('utf-8'))
conn.close() # Close the socket when done
print(data.decode("utf-8"))