简单通信

server.py

#  -*- coding: cp936 -*-
import  socket

if   __name__   ==   ' __main__ ' :
    sock 
=  socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.bind((
' 192.168.1.106 ' 8001 ))
    sock.listen(
5 )       # 最多允许5个客户连接到服务器,值至少为1
     while  True:
        
#  connection是一个新的socket对象,服务端通过它与客户端通信
         #  address是客户端的internet地址
        connection, address  =  sock.accept()      # 等待(waiting)状态
         print   ' connected from  ' , address
        
try :
            connection.settimeout(
5 )     # 设置超时时间
             #  recv时为阻塞(blocked)状态
            buf  =  connection.recv( 1024 # 接收的最大数据量为1024,如果超过则被截短
             if  buf  ==   ' 1 ' :
                connection.send(
' welcome to server! ' )
            
else :
                connection.send(
' please go out! ' )
        
except  socket.timeout:
            
print   ' time out '
        connection.close()


client.py

import  socket, time

if   __name__   ==   ' __main__ ' :
    sock 
=  socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.connect((
' 192.168.1.106 ' 8001 ))
    time.sleep(
2 )
    sock.send(
' 1 ' )
    
print  sock.recv( 1024 )
    sock.close



你可能感兴趣的:(简单通信)