阿尔海南粉 发表于 2017-4-26 12:50:48

Python_Socket_简单例子

  下面代码 还等待完善
  Server:

#!/usr/bin/env python
import socket
from time import ctime
import sys
import os
import subprocess
import commands

def main():
host = '192.168.1.111'   
port = 8888
buf_size = 1024
addr =(host, port)   
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)   
sock.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)      
sock.bind(addr)   
sock.listen(5)

while True:
print 'waiting for connection.........'      
connection,address = sock.accept()   
print "sock",connection.getpeername()
print '==============================='
print 'connection IP is :' ,address,"",

while True:         
recedata = connection.recv(buf_size)               
if not recedata:   
break
connection.send('[%s] :%s' %(ctime(),recedata))
print '_____________'
print recedata
print '______________'
instr=os.popen(recedata).readlines()      
for line in instr:
printline
connection.send(line)


if __name__ == '__main__':   
main()
  Clinet:

#!/usr/bin/env python
import socket
import time
import sys
def clint():
host = '192.168.1.111'
port = 8888
bufsize = 1024
addr = (host,port)
client = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
client.connect(addr)
while True:
data = raw_input('Enter:')
if data=='exit':
break
try:
if not data:
print "Use:command aveg aveg"
except:
break

client.send(data)

while 1:
try:
revcdata = client.recv(bufsize)
time.sleep(0.01)
print '------------'
print revcdata
print '------------'
if not revcdata:
break
except:
break



client.close()
if __name__ == '__main__':   
clint()
页: [1]
查看完整版本: Python_Socket_简单例子