Python脚本之socket
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python脚本之socket相关的知识,希望对你有一定的参考价值。
##############################################socket单线程
server端:
#!/usr/bin/env python
import socket,time,os
host=‘‘
port=18000
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.bind((host,port))
s.listen(1)
while 1:
conn,addr=s.accept()
print ‘connected by‘,addr
while 1:
data=conn.recv(8192)
cmd=os.popen(data)
cmd_smg=‘\033[32;1mFeedback of the cmd\033[0m\n‘+cmd.read()
if not data:break
#conn.sendall(data.upper())
conn.sendall(cmd_smg)
print ‘connected by‘,addr
#print ‘receievd cmd:‘%data.upper()
print cmd_smg
conn.close()
---------------------------------------------------
客户端:
#!/usr/bin/env python
#_*_ coding:utf-8 _*_
import socket,time,random,tab
host=‘192.168.1.10‘
port=18000
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.connect((host,port))
while 1:
#smg=random.randint(1,100)
cmd=raw_input(‘input cmd:‘)
#s.sendall(‘hello my name is xiaohong:%s‘%smg)
s.sendall(cmd)
data=s.recv(8192)
print "Received from server:",data
time.sleep(1.2)
s.close()
###################################################socket server多线程
server端
#!/usr/bin/env python
import SocketServer
class MyTCPHandle(SocketServer.BaseRequestHandler):
def handle(self):
while 1:
self.data=self.request.recv(8192)
if not self.data:
print ‘connected break‘
break
print ‘Connected from:‘,self.client_address
print self.data
self.request.sendall(self.data.upper())
host,port=‘‘,9999
server=SocketServer.ThreadingTCPServer((host,port),MyTCPHandle)
server.serve_forever()
-----------------------------------------------------
客户端:
#!/usr/bin/env python
#_*_ coding:utf-8 _*_
import socket,time,random,tab
host=‘192.168.1.10‘
port=9999
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.connect((host,port))
while 1:
#smg=random.randint(1,100)
cmd=raw_input(‘input cmd:‘)
cmd=cmd.strip()
if len(cmd)==0:continue
#s.sendall(‘hello my name is xiaohong:%s‘%smg)
s.sendall(cmd)
data=s.recv(8192)
print "Received from server:",data
#time.sleep(1.2)
s.close()
########################################################################
本文出自 “银河系|计算机网络” 博客,请务必保留此出处http://qqran.blog.51cto.com/10014850/1961981
以上是关于Python脚本之socket的主要内容,如果未能解决你的问题,请参考以下文章