学习python后写的关于网络编程,线程的例证

学习python后写的关于网络编程,线程的例子
该例子综合了python的网络编程,线程,异常处理,字符串处理,函数,类,做为入门级的例子,很
实用

服务器端server.py
#coding=utf-8
import socket
import threading
from time import sleep

class ThreadClass(threading.Thread):
  def setClient(self,client):
     self.client = client

  def run(self):
     print('threadname-->',self.getName())
     s = self.client.recv(1024).decode('utf-8')
     try:
       s = eval(s)
       s = str(s)
     except NameError:
       pass
     s = 'server deal result:' + s + "\n"
     self.client.send(s.encode('utf-8'))
     self.client.close()

if __name__=='__main__':
   s = socket.socket()
   host = socket.gethostname()
   port = 1234
   s.bind((host,port))
   #最多同时连5个客户端
   s.listen(5)
   while True :
        client,addr = s.accept()
        threadclass = ThreadClass()
        threadclass.setClient(client)
        threadclass.start()
        #sleep(20)
        #if threadclass.isAlive():
           #print('alive')
        #else:
           #print("notAlive")

客户端client.py
#coding=utf-8
import socket

def sendSource(source):
    return source.encode('utf-8')

def recvSource(source):
    return source.decode('utf-8')

def dealSource(source):
    try:
        s = socket.socket()
        s.connect(('10.9.9.12',1234))
        s.send(sendSource(source))
#缓冲区1k
        print(recvSource(s.recv(1024)))
    except socket.timeout:
        print("timeout")
    finally:
        s.close()

if __name__=='__main__':
   while True:
      source = input("input your source:\n")
      if str.strip(source)=="quit":#退出
         quit()
      else:#交给服务器处理
         dealSource(source)


几点需要注意:
1.代码里有中文的话要指定#coding=utf-8
2.命令行输入的数据要去空格str.strip(source)