预期目标:
(1)服务器地址、端口号通过终端传入
(2)服务器需要完成请求监听、接收数据、发送数据、断开连接
(3)客户端需要完成发送请求、接收响应,断开连接
服务器端程序代码:
#encoding:utf-8
import socket #导入socket包为了之后使用socket创建TCP服务端信息
import sys #导入sys包,为了之后从终端获取参数
def main():
if(len(sys.argv)<2):
print "Usage:<HOST Address> <PORT>"
exit(0)
else:
HOST=sys.argv[1]
PORT=int(sys.argv[2])
buffsize=1024
socket.setdefaulttimeout(100)
server=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
server.bind((HOST,PORT))
server.listen(5)
print "[*]Listening on %s:%d"%(HOST,PORT)
while True:
clientsock,clientaddress=server.accept()
print "Connect from:",clientaddress
while True:
recvdata = clientsock.recv(buffsize).decode('utf-8')
if recvdata == 'exit':
break
print recvdata
senddata = raw_input("input the message you want to send ")
clientsock.send(senddata.encode())
clientsock.close()
server.close()
if __name__ == '__main__':
main()
客户端程序代码:
#encoding:utf-8
import socket
import sys
def main():
if len(sys.argv)<3:
print("Usage:<Server Host> <Server Port>")
exit()
else:
HOST=sys.argv[1]
PORT=int(sys.argv[2])
socket.setdefaulttimeout(10)
client=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
client.connect((HOST,PORT))
while True:
senddate=raw_input("input the message you want to send or input exit to quite!")
if senddate=='exit':
break
client.send(senddate)
recvdata=client.recv(1024).decode('utf-8')
print recvdata
client.close()
if __name__ == '__main__':
main()
运行实例:
服务器端:
客户端:
注:是在python 2.7版本上运行!