#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()
C/S通讯模型
最新推荐文章于 2024-08-22 19:27:13 发布