连接客户端到服务器,python
我的服务器和客户端出现问题。我需要客户端将信息发送到服务器,服务器将信息发送回服务器,然后该过程再次重复。我能够让客户端连接到服务器,并在第一轮发送信息,但我似乎不知道如何让服务器在使用conn.shutdown(1)功能关闭发送端后再次侦听客户端。我尝试再次连接到端口,但出现一个错误,显示“传输端点已连接”。有什么建议吗?尝试使用线程(多线程)- 服务器应用程序连接客户端到服务器,python,python,sockets,client,server,Python,Sockets,Client,Server,我的服务器和客户端出现问题。我需要客户端将信息发送到服务器,服务器将信息发送回服务器,然后该过程再次重复。我能够让客户端连接到服务器,并在第一轮发送信息,但我似乎不知道如何让服务器在使用conn.shutdown(1)功能关闭发送端后再次侦听客户端。我尝试再次连接到端口,但出现一个错误,显示“传输端点已连接”。有什么建议吗?尝试使用线程(多线程)- 服务器应用程序 #!/usr/bin/python # This is server.py file import socke
#!/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
客户端应用程序
#!/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
可能重复为什么要在连接完成之前关闭?默认情况下,一个刚刚关闭的套接字将在一段时间内处于“使用中”状态,以防出现散乱的数据包——这是可以解决的,但这是不可取的,除非在极少数情况下它是必不可少的,而你的套接字似乎不是,因为你可以避免过早关闭,不是吗?