python简单的socket 服务器和客户端

服务器端代码

if "__main__" == __name__:

    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();
        print("get client");
        print(addr);
            
        conn.settimeout(5);
        szBuf = conn.recv(1024);
        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");

 

 

转自:http://andylin02.iteye.com/blog/939884

posted @ 2015-04-23 15:49  wangxusummer  阅读(5100)  评论(0编辑  收藏  举报