ironpython 线程和socket通信
ironpython不同于python中的线程和socket调用方式
ironpython中使用线程 调用的模板为System.Threading
python中 使用线程 调用的模板为 threading
socke服务端:
#encoding: gb2312 import clr import sys from System import * from System.Threading import Thread, ThreadStart import socket HOST='127.0.0.1' PORT = 8888 def serverThread(): s=socket.socket(socket.AF_INET,socket.SOCK_STREAM) s.bind((HOST,PORT)) s.listen(10) while 1: print "Listening activated now starting to accept" conn,addr=s.accept() sIn=conn.recv(1024) sIn=sIn.decode('gb2312') print "recv data:"+sIn sOut=cope_with(sIn) #cope_with(s) deal function sLen='%04d'%len(sOut) #print "sout length:"+sLen sOutData=length+sOut sOutData=sOutData.encode('gb2312') print "outResult:"+sOutData conn.send(sOutData) print "connection closing" conn.close() print "connection closed" t=Thread(ThreadStart(serverThread)) t.Start()
由于ironpython编码方式不支持UTF-8 所以在这里小弟只能使用gb2312编码方式
ironpython编码为 str.encode("gb2312")
ironpython解码为 str.decode("gb2312")
用threading 做socket通信, 启动的方式为 t=Thread(ThreadStart(your function's name)) t.Start()
ironpython socket通信 client 客户端示例:
#encoding: gb2312 from System.Threading import Thread,ThreadStart import socket import sys import clr clr.AddReferenceToFile("testdll.dll") from testdll import * HOST='127.0.0.1' PORT = 8888 def clientThread(): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) print 'Client connecting' s.connect((HOST , PORT)) sIn="hello 哦我们" sIn=sIn.encode('gb2312') s.send(sIn) print 'Connection formed, now starting recv' sOut=s.recv(512) sOut=sOut.decode('gb2312') print sOut print 'Client closing' s.close() print 'Client closed' t2 = Thread(ThreadStart(clientThread)) t2.Start()