用python做socket编程,从实现上来讲,是非常简单的。下面是从他的帮助文档里面取出来的两段代码,显示了服务端和客户端。
服务端:
# Echo server program
import socket
HOST = '127.0.0.1' # Symbolic name meaning the local host
PORT = 50007 # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)
conn, addr = s.accept()
print 'Connected by', addr
while 1:
data = conn.recv(1024)
if not data: break
conn.send(data)
conn.close()
|
客户端:
# Echo client program
import socket
HOST = '127.0.0.1' # The remote host
PORT = 50007 # The same port as used by the server
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
s.send('Hello, world')
data = s.recv(1024)
s.close()
print 'Received', repr(data)
|
很简单的代码,在服务端启动程序后,进入消息等待循环。当客户端连接后并发送消息,而在服务端收到消息后,发送消息,并在客户端及服务端关闭socket.
阅读(1114) | 评论(1) | 转发(0) |