我的服务器和客户端出现问题。我需要客户端将信息发送到服务器,服务器将信息发回,并再次重复该过程。我能够让客户端连接到服务器并在第一轮发送信息但我似乎无法弄清楚如何让我在使用函数conn.shutdown关闭发送端后再次收听客户端( 1)。我尝试再次连接到端口,但是我收到一条错误消息“传输端点已经连接”。有什么建议吗?
答案 0 :(得分:1)
尝试使用线程(多线程) -
服务器应用
#!/usr/bin/python # This is server.py file
import socket # Import socket module
s = socket.socket() # Create a socket object
host = socket.gethostname() # Get local machine name
port = 12345 # Reserve a port for your service.
s.bind((host, port)) # Bind to the port
s.listen(5) # Now wait for client connection.
def clientthread(conn):
conn.send('connected')
try:
while True:
data = conn.recv(1024)
processData(conn,data)
if not data:
break
except Exception as ex:
print ex
conn.close()
while True:
conn, addr = s.accept()
print 'Got connection from', addr
thread.start_new_thread(clientthread ,(conn,))
s.close()
客户端应用
#!/usr/bin/python # This is client.py file
import socket # Import socket module
s = socket.socket() # Create a socket object
host = socket.gethostname() # Get local machine name
port = 12345 # Reserve a port for your service.
s.connect((host, port))
print s.recv(1024)
s.close # Close the socket when done