演示python服务器客户端交互

时间:2013-06-21 00:34:02

标签: python networking

我对网络一般都很陌生,我正在尝试在python服务器和客户端之间建立一个简单的交换。

这是服务器的代码

import socket, ssl

def do_something(connstream, data):
print "HALLO"

def deal_with_client(connstream):
    data = connstream.read()
    # null data means the client is finished with us
    while data:
        if not do_something(connstream, data):
            # we'll assume do_something returns False
            # when we're finished with client
            break
         data = connstream.read()
     # finished with client

bindsocket = socket.socket()
bindsocket.bind(('127.0.0.1', 10024))
bindsocket.listen(5)


while True:
    newsocket, fromaddr = bindsocket.accept()
    print "Setting up connection"
    connstream = ssl.wrap_socket(newsocket,
                             server_side=True,
                             ca_certs=None,
                             certfile="cert.pem",
                             keyfile="privatekey.pem",
                             ssl_version=ssl.PROTOCOL_TLSv1)
    try:
        deal_with_client(connstream)
    finally:
        connstream.shutdown(socket.SHUT_RDWR)
        connstream.close()

以下是client.py

的代码
 import socket, ssl

 clientsocket = socket.socket()
 ssl_sock = ssl.wrap_socket(clientsocket,
                       certfile="cert.pem",
                       cert_reqs=ssl.CERT_REQUIRED)
 ssl_sock.connect(('127.0.0.1', 10024))

 print ssl_sock.getpeername()
 print ssl_sock.getpeercert()

 data = ssl_sock.recv(1024)
 ssl_sock.close()

 print 'Received', repr(data)

我使用openssl生成了“cert.pem”和“privatekey.pem”。

Traceback (most recent call last):
 File "server.py", line 30, in <module>
    ssl_version=ssl.PROTOCOL_TLSv1)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ssl.py", line 344, in wrap_socket
    ciphers=ciphers)
   File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ssl.py", line 121, in __init__
    self.do_handshake()
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ssl.py", line 283, in do_handshake
    self._sslobj.do_handshake()
 ssl.SSLError: [Errno 8] _ssl.c:499: EOF occurred in violation of protocol

我想知道是否知道更多的人能指出我正确的方向。我真的想用SSL btw来做这件事,但如果这是更好的方法,我愿意切换到TLS。

1 个答案:

答案 0 :(得分:0)

可能是套接字没有使用兼容的ssl版本运行,你应该在你的客户端中放置一个“ssl.PROTOCOL_TLSv1”兼容版本(或者从服务器中删除它并使用默认值)。 谷歌搜索你可以找到许多套接字通信的例子