我正在阅读Python 2.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
2 回答
TCP套接字是双向的 . 因此,在连接之后,服务器和客户端之间没有区别,您只有一个流的两端:
和客户:
上面的答案会引发错误:
TypeError: a bytes-like object is required, not 'str'
但是,以下代码对我有用:server.py
client.py: