Python_Socket_簡単な例

3106 ワード

次のコードはまだ完備を待っています.
 
 
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:
              print  line
	      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[1] aveg[2]"
                   
          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()