python简单的socket 服务器和客户端 分类: socket 2013-08-10 16:44 455人阅读 评论(0) 收藏

服务器端代码:

if "__main__" == __name__:
    import socket
    try:
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM);
        print("create socket succ!");
        
        sock.bind(('localhost', 8001));
        print("bind socket succ!");
        
        sock.listen(5);
        print("listen succ!");

    except:
        print("init socket err!");

    while True:
        print("listen for client...");
        conn, addr = sock.accept(); #socket.accept():返回(conn,address)对,其中conn是新的socket对象,在其上可以发送和接收数据;address是另一端的socket地址
        print("get client");
        print(addr);
            
        conn.settimeout(5);
        szBuf = conn.recv(1024);#使用sock.accept()创建的socket对象,
        print("recv:" + szBuf);

        if "0" == szBuf:
            conn.send('exit');
        else:
            conn.send('welcome client!');

        conn.close();
        print("end of sevice");
    

客户端代码:
#!/usr/bin/env python

import socket;

if "__main__" == __name__:
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM);
    sock.connect(('localhost', 8001));
    sock.send('0');

    szBuf = sock.recv(1024);
    print("recv " + szBuf);
    sock.close();
    print("end of connect");



posted @ 2013-08-10 16:44  前行者2011  阅读(143)  评论(0编辑  收藏  举报