Python网络编程socket练习(TCP)
服务器端:server.py
# -*- coding: utf-8 -*-
from socket import *
HOST=''
PORT=5000
BUFF_SIZE=1024
ADDR=(HOST,PORT)
serTCP=socket(AF_INET,SOCK_STREAM)
serTCP.bind(ADDR)
serTCP.listen(5)
while True:
print 'waiting for connect...'
cliTcp,addr=serTCP.accept()
print 'successful connect from ',addr
while True:
try:
data=cliTcp.recv(BUFF_SIZE)
if not data.strip():
break
print data
cliTcp.send(data)
except:
print 'client has exit!'
break
cliTcp.close()
serTCP.close()
raw_input("press enter")
客户端:client.py
# -*- coding: utf-8 -*-
from socket import *
HOST='127.0.0.1'
PORT=5000
BUFF_SIZE=1024
ADDR=(HOST,PORT)
try:
cliTcp=socket(AF_INET,SOCK_STREAM)
cliTcp.connect(ADDR)
print 'successful connect'
except:
print 'faild linked'
else:
while True:
data=raw_input('input your messsage >')
if not data.strip(): #如果数据为空则关闭连接
break
cliTcp.send(data)
data2=cliTcp.recv(BUFF_SIZE) #接收来自服务器的数据
if not data2.strip():
break
print data2
cliTcp.close()
欢迎来邮件交流:lq65535@163.com