如何在python中将消息从客户端发送到服务器
问题描述
我正在阅读Python2.7.10中具有客户端和服务器的两个程序。如何修改这些程序以将邮件从客户端发送到服务器?
server.py:
#!/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.
while True:
c, addr = s.accept() # Establish connection with client.
print 'Got connection from', addr
c.send('Thank you for connecting')
c.close() # Close the connection
client.py:
#!/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 = 80 # Reserve a port for your service.
s.connect((host, port))
print s.recv(1024)
s.close # Close the socket when done
解决方案
套接字是双向的。所以连接后,服务器和客户端没有区别,只有流的两端:
import socket # Import socket module
s = socket.socket() # Create a socket object
s.bind(('0.0.0.0', 12345)) # Bind to the port
s.listen(5) # Now wait for client connection.
while True:
c, addr = s.accept() # Establish connection with client.
print 'Got connection from', addr
print c.recv(1024)
c.close() # Close the connection
和客户端:
import socket # Import socket module
s = socket.socket() # Create a socket object
s.connect(('localhost', 12345))
s.sendall('Here I am!')
s.close() # Close the socket when done
相关文章