[python&php 网络编程]完整的socket服务端客户端

1.python服务端

import socket
import argparse

host = 'localhost'
data_payload = 2048
backlog = 5 


def echo_server(port):
    """ A simple echo server """
    # Create a TCP socket
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    # Enable reuse address/port 
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    # Bind the socket to the port
    server_address = (host, port)
    print "Starting up echo server  on %s port %s" % server_address
    sock.bind(server_address)
    # Listen to clients, backlog argument specifies the max no. of queued connections
    sock.listen(backlog) 
    while True: 
        print "Waiting to receive message from client"
        client, address = sock.accept() 
        data = client.recv(data_payload) 
        if data:
            print "Data: %s" %data
            client.send(data)
            print "sent %s bytes back to %s" % (data, address)
        # end connection
        client.close() 
   
if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Socket Server Example')
    parser.add_argument('--port', action="store", dest="port", type=int, required=True)
    given_args = parser.parse_args() 
    port = given_args.port
    echo_server(port)

2.python客户端

import socket
import argparse

host = 'localhost'

def echo_client(port):
    """ A simple echo client """
    # Create a TCP/IP socket
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    # Connect the socket to the server
    server_address = (host, port)
    print "Connecting to %s port %s" % server_address
    sock.connect(server_address)
    
    # Send data
    try:
        # Send data
        message = "Test message. This will be echoed"
        print "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 "Received: %s" % data
    except socket.errno, e:
        print "Socket error: %s" %str(e)
    except Exception, e:
        print "Other exception: %s" %str(e)
    finally:
        print "Closing connection to the server"
        sock.close()
    
if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Socket Server Example')
    parser.add_argument('--port', action="store", dest="port", type=int, required=True)
    given_args = parser.parse_args() 
    port = given_args.port
    echo_client(port)

启动服务端,由于用了pasrearg模块 因此需要 在启动命令后面加上 --port = 8888 来指定某个端口,然后再运行客户端脚本,发现在两边都会有信息输出,客户端发送完后关闭socket,服务端则一直监听8888端口。


3.php服务端


4.php客户端


php码出来的代码风格没python那么优雅(也可能是我偷懒) 但都差不多,码socket不会比写业务逻辑高级,都是码代码,php也用cli方式运行,用cgi方式跑又不设置超时时间的话 会超时的.

5.UDP php服务端


6.UDP php客户端


php官方文档在udp socket方面没有完整的例子,这里贴一个备用吧 :)

转载请标注原文地址:http://blog.csdn.net/ddjohn/article/details/50041763

你可能感兴趣的:(python,php)