一个简单的TCP客户端与服务器
服务器端功能:监听本地50007端口,最多处理5个客户请求,接收来自客户端的消息,并反射回去。
#!/usr/bin/env python
#########################################################
# Server side: open a socket on a port, listen for
# a message from a client, and send an echo reply;
# this is a simple one-shot listen/reply per client,
# but it goes into an infinite loop to listen for
# more clients as long as this server script runs;
#########################################################
from socket import * # get socket constructor and constants
myHost = '' # server machine, '' means local host
myPort = 50007 # listen on a non-reserved port number
sockobj = socket(AF_INET, SOCK_STREAM) # make a TCP socket object
sockobj.bind((myHost, myPort)) # bind it to server port number
sockobj.listen(5) # listen, allow 5 pending connects
while 1: # listen until process killed
connection, address = sockobj.accept() # wait for next client connect
print 'Server connected by', address # connection is a new socket
while 1:
data = connection.recv(1024) # read next line on client socket
if not data: break # send a reply line to the client
connection.send('Echo=>' + data) # until eof when socket closed
connection.close()
客户端功能:连接至服务器,向服务器发送消息,并显示服务器返回的消息。
#!/usr/bin/env python
#############################################################
# Client side: use sockets to send data to the server, and
# print server's reply to each message line; 'localhost'
# means that the server is running on the same machine as
# the client, which lets us test client and server on one
# machine; to test over the Internet, run a server on a remote
# machine, and set serverHost or argv[1] to machine's domain
# name or IP addr; Python sockets are a portable BSD socket
# interface, with object methods for standard socket calls;
#############################################################
import sys
from socket import * # portable socket interface plus constants
serverHost = 'localhost' # server name, or: 'starship.python.net'
serverPort = 50007 # non-reserved port used by the server
message = ['Hello network world'] # default text to send to server
if len(sys.argv) > 1:
serverHost = sys.argv[1] # or server from cmd line arg 1
if len(sys.argv) > 2: # or text from cmd line args 2..n
message = sys.argv[2:] # one message for each arg listed
sockobj = socket(AF_INET, SOCK_STREAM) # make a TCP/IP socket object
sockobj.connect((serverHost, serverPort)) # connect to server machine and port
for line in message:
sockobj.send(line) # send line to server over socket
data = sockobj.recv(1024) # receive line from server: up to 1k
print 'Client received:', `data`
sockobj.close() # close socket to send eof to server
代码来自>