一、python中socket简介
1、Socket 类型
2、Socket 函数
二、python中编写简单client和server
代码示例:
1 #server.py 2 3 import socket 4 5 def Server(): 6 sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM) 7 sock.bind(('localhost',8080)) 8 sock.listen(1) 9 10 while True: 11 connection, address=sock.accept() 12 try: 13 connection.settimeout(1) 14 buf=connection.recv(1024) 15 if buf=='1': 16 connection.send('Welcome to server!') 17 else: 18 connection.send('Goodbye!') 19 except socket.timeout: 20 print 'socket timeout' 21 connection.close() #注意connection.close()的结束位置。 22 23 if __name__=='__main__': 24 Server() 25 26 27 #client.py 28 29 import socket 30 import time 31 32 def Client(): 33 sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM) 34 sock.connect(('localhost',8080)) 35 time.sleep(2) 36 sock.send('1') 37 print sock.recv(1024) 38 sock.close() 39 40 if __name__=='__main__': 41 Client()
三、python通过socket传输对象
python可以通过send发送byte字节,其实可以利用send发送python中的对象,可以有两种方法(1)通过struct模块(2)通过pickle模块:
通过struct模块
1 import socket 2 import struct 3 4 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 5 sock.connect(('localhost', 10000)) 6 7 values = (1, 'ab', 2.7) 8 packer = struct.Struct('I 2s f') 9 packed_data = packer.pack(*values) 10 11 try: 12 sock.sendall(packed_data) 13 finally: 14 sock.close()
通过pickle方法:
try: import cPickle as pickle except: import pickle class AA(): def a(self): print "123" ddd = AA() data = pickle.dumps(ddd)
注意采用pickle方法,接收时要采用pickle.loads(data)才行。load和loads,dump和dumps的区别就是一个读文件的,里面有readline,一个是读字符串的,没有readline。
python还有单独的库,提供了通过网络传输对象Pyro4 4.32库,但是由于不需要那么复杂,所以没有细看,网址:https://pypi.python.org/pypi/Pyro4
四、python接收不定长数据
python处理不定长数据可以通过简单的while True,然后不停接收就可以了。当最后一次接收时长度变成0就可以退出了。
同时还有另一种方法获取socket等信息。
socket.getaddrinfo(host, port, family=0, socktype=0, proto=0, flags=0)
自己编写程序部分代码示例(注意不可以直接运行,因为调用了我自己写的其他模块干别的事情):
1 #server.py 2 import socket 3 import sys 4 from CalculateSize import Calculator 5 import cPickle as pickle 6 7 HOST = None # Symbolic name meaning all available interfaces 8 PORT = 8888 # Arbitrary non-privileged port 9 s = None 10 for res in socket.getaddrinfo(HOST, PORT, socket.AF_UNSPEC, 11 socket.SOCK_STREAM, 0, socket.AI_PASSIVE):
- #根据给定的参数host/port,相应的转换成一个包含用于创建socket对象的五元组,
- #参数host为域名,以字符串形式给出代表一个IPV4/IPV6地址或者None.
- #参数port如果字符串形式就代表一个服务名,比如“http”"ftp""email"等,或者为数字,或者为None
- #参数family为地主族,可以为AF_INET ,AF_INET6 ,AF_UNIX.
- #参数socketype可以为SOCK_STREAM(TCP)或者SOCK_DGRAM(UDP)
- #参数proto通常为0可以直接忽略
- #参数flags为AI_*的组合,比如AI_NUMERICHOST,它会影响函数的返回值
- #附注:给参数host,port传递None时建立在C基础,通过传递NULL。
- #该函数返回一个五元组(family, socktype, proto, canonname, sockaddr),同时第五个参数sockaddr也是一个二元组(address, port)
12 af, socktype, proto, canonname, sa = res 13 try: 14 s = socket.socket(af, socktype, proto) 15 except socket.error, err_msg: 16 print err_msg 17 s = None 18 continue 19 try: 20 s.bind(sa) 21 s.listen(5) 22 except socket.error, err_msg: 23 print err_msg 24 s.close() 25 s = None 26 continue 27 break 28 if s is None: 29 print 'could not open socket' 30 sys.exit(1) 31 32 while 1: 33 conn, addr = s.accept() 34 #conn.settimeout(10) 35 storage=Calculator() 36 storage.process() 37 ParttionSizeDict=storage.partitionsize 38 storagedata=pickle.dumps(ParttionSizeDict) 39 print 'Connected by', addr 40 print len(storagedata) 41 data = conn.recv(1024) 42 #if not data: break 43 conn.send(storagedata) 44 conn.close()
1 #client.py 2 import socket 3 import sys 4 import cPickle as pickle 5 6 HOST = '127.0.0.1' # The remote host 7 PORT = 8888 # The same port as used by the server 8 s = None 9 for res in socket.getaddrinfo(HOST, PORT, socket.AF_UNSPEC, socket.SOCK_STREAM): 10 af, socktype, proto, canonname, sa = res 11 try: 12 s = socket.socket(af, socktype, proto) 13 except socket.error, msg: 14 s = None 15 continue 16 try: 17 s.connect(sa) 18 except socket.error, msg: 19 s.close() 20 s = None 21 continue 22 break 23 if s is None: 24 print 'could not open socket' 25 sys.exit(1) 26 27 s.sendall('Hello, world') 28 data ='' 29 #s.settimeout(2) 30 #len=s.recv(1024) 31 while True: #注意如何处理不定长 32 data1 = s.recv(1024) 33 print len(data1) 34 data += data1 35 if len(data1)==0: 36 break 37 storageDataDick=pickle.loads(data) 38 39 print storageDataDick 40 s.close() 41 print 'Received'