# Create a TCP/IP socket sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Bind the socket to the port server_address = ('localhost', 10000) print >>sys.stderr, 'starting up on %s port %s' % server_address sock.bind(server_address) # Calling listen() puts the socket into server mode, and accept() waits for an # incoming connection. # Listen for incoming connections sock.listen(1)
whileTrue: # Wait for a connection print >>sys.stderr, 'waiting for a connection' connection, client_address = sock.accept() try: print >>sys.stderr, 'connection from', client_address # Receive the data in small chunks and retransmit it whileTrue: data = connection.recv(16) print >>sys.stderr, 'received "%s"' % data if data: print >>sys.stderr, 'sending data back to the client' connection.sendall(data) else: print >>sys.stderr, 'no more data from', client_address break finally: # Clean up the connection connection.close()
# Connect the socket to the port where the server is listening server_address = ('localhost', 10000) print >>sys.stdout, 'connecting to %s port %s' % server_address sock.connect(server_address)
try: # Send data message = 'This is the message. It will be repeated.' print >>sys.stderr, 'sending "%s"' % message sock.sendall(message)
# Look for the response amount_received = 0 amount_expected = len(message)
while amount_received < amount_expected: data = sock.recv(16) amount_received += len(data) print >>sys.stderr, 'received "%s"' % data finally: print >>sys.stderr, 'closing socket' time.sleep(20) # For netstat sock.close()
# Create a TCP/IP socket sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Connect the socket to the port where the server is listening server_address = ('localhost', 10000) print >>sys.stdout, 'connecting to %s port %s' % server_address sock.connect(server_address)
try: # Send data message = 'This is the message. It will be repeated.' print >>sys.stderr, 'sending "%s"' % message sock.sendall(message)
# Look for the response amount_received = 0 amount_expected = len(message)
while amount_received < amount_expected: data = sock.recv(16) amount_received += len(data) print >>sys.stderr, 'received "%s"' % data finally: print >>sys.stderr, 'closing socket' sock.close()
启动服务:
此时的netstat:
启动echo_client_tcp_child.py:
此时的netstat:
观察lsof输出,可以发现子进程已经继承了父进程的sock。
$ lsof -p 16696 COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME cat 16696 xikangjie 3u sock 0,7 0t0 13005348 can't identify protocol