简体   繁体   中英

Whether to use http.client or Socket package in Python?

I am working on project where I need to send encrypted data to server over network. I have searched over internet and checked few programs but I am confused between two packages http.client and Socket earlier I thought both are same thing.

Few lines from my code-

import http.client
.
.
ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
conn = http.client.HTTPSConnection(host="wwww.my_server.com", port=443, context=ctx)
headers = {'Content-type': 'application/json'}
json_data = json.dumps(System_info)
conn.request('POST', '/post', json_data, headers)

The above method works without certificates , certificate part is pending.

The other method which I found is using Sockets-

import Socket
.
.
context = ssl.create_default_context(ssl.Purpose.SERVER_AUTH, cafile=server_cert)
context.load_cert_chain(certfile=client_cert, keyfile=client_key)

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
conn = context.wrap_socket(sock=s, server_side=False, do_handshake_on_connect=True, server_hostname=server_sni_hostname)
conn.connect((host_addr, host_port))

I was able to run these above code on my system where both my system was client and server.

However I wanted to know what should I use as I want to send the data to NMS server which must be encrypted and secure.

Additional Info-

Os - Ubuntu 16
Python 3.5

What you need to use depends on your actual but unknown requirements: libraries like http.client or requests implement the HTTP protocol, both for plain HTTP and with TLS (ie HTTPS). These modules are build on top of sockets.

If the application protocol spoken with your specific server is HTTP/HTTPS then you might use higher level libraries like http.client and requests but you might in theory also use sockets. Only, using plain sockets makes it much more complex to implement for you and it will be very likely less robust and take more time to implement than using established higher level libraries.

If your server does not support HTTP/HTTPS you need to either implement the specific (unknown to us) protocol required by the server yourself using plain sockets, or you need to find some library which already implements the protocol required by the server. The latter is preferred in most cases.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM