python客户端与服务器端的通信

Server.py:

'''
    Created on 2015年3月7日
    
    @author: pangbin2415
    '''
import socket
sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM) # 生成socket对象
sock.bind(('localhost', 8001))                          #绑定主机ip和端口号
sock.listen(5)
while True:
    connection,addr = sock.accept()                     #接受客户端的连接
    try:
        connection.settimeout(5)
        buf = connection.recv(1024)
        if buf == 1:
            connection.send('welcome to server!')      #向客户端发送一个字符串信息
        else:
            connection.send("Failed")
    except socket.timeout:                             #如果出现超时
        print 'time out'
    connection.close()

Client.py

'''
Created on 2015年3月7日

@author: pangbin2415
'''
import socket
import time
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(('localhost', 8001))
time.sleep(2)
sock.send('1')
print sock.recv(1024)


你可能感兴趣的:(python学习笔记)