我一直在关注Python中的服务器和客户端通信的示例,但我不能让服务器不断地收听新消息,打印它们并将它们发回给客户端以便打印它。我有什么想法,我做错了什么? 服务器代码:
#Imports
import socket
#Define socket address
TCP_IP = '0.0.0.0' # consider all incoming IPs
TCP_PORT = 5000 # port# communicating with the client
BUFFER_SIZE = 1024 # buffer size for receiving data
#Create socket IPv4 TCP
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print "Socket created"
s.bind((TCP_IP, TCP_PORT))
s.listen(20)
print "Waiting for a Cli_socket..."
#Wait for Cli_sockect
while True:
while True:
# accept Cli_sockection
Cli_sock, addr = s.accept()
print "Cli_sockected with " + addr[0] + " " + str(addr[1])
# get message from client
message = Cli_sock.recv(BUFFER_SIZE)
print message
# check that there is a message
if not message:
break
# send message to client
Cli_sock.send(message)
print "Sent message"
s.close()
print "Socket Closed"
客户代码:
# a simple client socket
import socket
# define socket address
TCP_IP = '127.0.0.1' # ip of connecting server
TCP_PORT = 5000 # port communicating server
BUFFER_SIZE = 1024 # buffer size receiving data
# create socket IPv4 & TCP protocol
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print "Socket created successfully."
# connect to server
s.connect((TCP_IP, TCP_PORT))
print "Established connection with the server."
data = s.recv(BUFFER_SIZE)
while True:
print ("Message to send:")
message = raw_input()
s.send(message)
print "Message sent to server: %s." % message
print ("Message Recv:%s\n" % data)
答案 0 :(得分:0)
您的服务器在发送任何内容之前正在等待来自客户端的数据:
Cli_sock, addr = s.accept()
print "Cli_sockected with " + addr[0] + " " + str(addr[1])
# get message from client
message = Cli_sock.recv(BUFFER_SIZE)
您的客户端在发送任何内容之前正在等待来自服务器的数据:
s.connect((TCP_IP, TCP_PORT))
print "Established connection with the server."
data = s.recv(BUFFER_SIZE)
因此两者都在等待彼此发送数据,但没有人这样做。这就是它挂起的原因。