gpt4 book ai didi

python - Python 中的客户端-服务器通信

转载 作者:太空宇宙 更新时间:2023-11-04 00:34:30 26 4
gpt4 key购买 nike

我已经建立了客户端-服务器通信。

问题是我不能发送多条消息,我试图修复它,但我不知道出了什么问题。

这是我的代码:

**服务器代码和客户端代码在两个不同的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"))

有人可以帮忙吗?

最佳答案

添加了一点保护的服务器端。也许这就是您所需要的?服务器将在客户端进程完成后继续监听连接。通过启动服务器、启动客户端、发送消息、再次启动客户端并发送另一条消息来尝试...

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

关于python - Python 中的客户端-服务器通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44662178/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com