服务器端代码

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 "" == 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(''); szBuf = sock.recv(1024);
print("recv " + szBuf);
sock.close();
print("end of connect");

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

05-11 18:25