C/S通讯模型

#server端:
"""
服务端创建socket步骤:
1、创建socket对象 -> 2、绑定Ip及端口号 -> 
3、监听端口号,等待客户端请求 ->响应客户端请求
"""

import socket
import time
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print type(sock)
sock.bind(('localhost', 8001)) #绑定IP地址和端口号
sock.listen(5)
while True:

    thistime=time.strftime('%Y-%m-%d-%H-%M-%S',time.localtime())
    try:
        connection,address = sock.accept()
        print type(connection)
        print type(address)
        print "address:", address
        print "------------------------"

        connection.settimeout(5)#设置超时间
        buf = connection.recv(1024) #设置接收长度
        print (thistime+"接收到:"+buf+"")
        connection.send(thistime+':'+buf)
    except socket.timeout:
        print 'time out'
    connection.close()

 #client端:
import socket
HOST = 'localhost' #绑定的IP
PORT = 8001 #绑定的端口

"""
客户端连接服务端步骤:
1、创建客户端socket对象 -> 2、创建与服务端的连接 -> 3、发送信息 -> 4、处理服务端的返回信息
"""
while True:
    temp=raw_input("输入任意字符发送:")
    if temp=="exit":
        break
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    strd=temp+""
    s.connect((HOST, PORT))
    s.send(strd+"")
    data = s.recv(1024)
    print data
    s.close()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值