VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > temp > 简明python教程 >
  • python基础(30):黏包、socket的其他方法(5)

('utf-8'),
  • shell=True,
  • stdout=subprocess.PIPE,
  • stderr=subprocess.PIPE)
  • err=res.stderr.read()
  • print(err)
  • if err:
  • back_msg=err
  • else:
  • back_msg=res.stdout.read()
  •  
  • conn.send(struct.pack('i',len(back_msg))) #先发back_msg的长度
  • conn.sendall(back_msg) #在发真实的内容
  •  
  • conn.close()
  • client:

    
    	
    1. #_*_coding:utf-8_*_
    2. import socket,time,struct
    3.  
    4. s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    5. res=s.connect_ex(('127.0.0.1',8080))
    6.  
    7. while True:
    8. msg=input('>>: ').strip()
    9. if len(msg) == 0:continue
    10. if msg == 'quit':break
    11.  
    12. s.send(msg.encode('utf-8'))
    13.  
    14. l=s.recv(4)
    15. x=struct.unpack('i',l)[0]
    16. print(type(x),x)
    17. # print(struct.unpack('I',l))
    18. r_s=0
    19. data=b''
    20. while r_s < x:
    21. r_d=s.recv(1024)
    22. data+=r_d
    23. r_s+=len(r_d)
    24.  
    25. # print(data.decode('utf-8'))
    26. print(data.decode('gbk')) #windows默认gbk编码

    我们还可以把报头做成字典,字典里包含将要发送的真实数据的详细信息,然后json序列化,然后用struck将序列化后的数据长度打包成4个字节(4个自己足够用了)。

     server:

    
    	
    1. import socket
    2. import struct
    3. import json
    4. import subprocess
    5. import os
    6.  
    7. class MYTCPServer:
    8. address_family = socket.AF_INET
    9.  
    10. socket_type = socket.SOCK_STREAM
    11.  
    12. allow_reuse_address = False
    13.  
    14. max_packet_size = 8192
    15.  
    16. coding='utf-8'
    17.  
    18. request_queue_size = 5
    19.  
    20. server_dir='file_upload'
    21.  
    22. def __init__(self, server_address, bind_and_activate=True):
    23. """Constructor. May be extended, do not override."""
    24. self.server_address=server_address
    25. self.socket = socket.socket(self.address_family,
    26. self.socket_type)
    27. if bind_and_activate:
    28. try:
    29. self.server_bind()
    30. self.server_activate()
    31. except:
    32. self.server_close()
    33. raise
    34.  
    35. def server_bind(self):
    36. """Called by constructor to bind the socket.
    37. """
    38. if self.allow_reuse_address:
    39. self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    40. self.socket.bind(self.server_address)
    41. self.server_address = self.socket.getsockname()
    42.  
    43. def server_activate(self):
    44. """Called by constructor to activate the server.
    45. """
    46. self.socket.listen(self.request_queue_size)
    47.  
    48. def server_close(self):
    49. """Called to clean-up the server.
    50. """
    51. self.socket.close()
    52.  
    53. def get_request(self):
    54. """Get the request and client address from the socket.
    
    相关教程