python:线程Thread-1

时间:2017-06-15 05:19:35

标签: python server eof imaplib

我正在python3.3中开发客户端服务器代码。 它工作得很好,我没有改变任何东西,但是当我运行它时突然出现这个异常:“Thread-1中的异常:”并且它发送了这个错误:“imaplib.abort:套接字错误:EOF“。我真的不知道它。 这是我的服务器代码:

from __future__ import unicode_literals
from imapclient import IMAPClient
from threading import Thread
import socket
import smtplib


# Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Bind the socket to the port
server_address = ('localhost', 100)
print('Server: starting up on {} port {}'.format(*server_address))
sock.bind(server_address)
# Listen for incoming connections

sock.listen(1)

threads_count = 0



def response(connection):
    global threads_count
    threads_count += 1
    username = ''
    password = ''
    print('Server: Thread {}: started.'.format(threads_count))
    try:
        while  1:
            # Receive the data in small chunks and retransmit it
            data = connection.recv(4096).decode('utf-8')
            #print('Server: Thread {}: received "{}"'.format(threads_count, data))

            # mail = imaplib.IMAP4_SSL('sara@test.com')
            # mail.login('email', 'pswd')
            if data[:5] == 'login':
                data = connection.recv(4096).decode('utf-8')
                username = data[0:data.rfind(":")]
                password = data[data.find(":")+1:len(data)-1]
                print(username)
                print(password)
                data = "Login Successfully"
                connection.sendall(data.encode())


            if data[:4] == 'send':
                sender = username
                data = connection.recv(4096).decode('utf-8')
                receivers = data[:data.find(":")]
                msg = ('from "%s"' %sender + 'to "%s"' %receivers)

                print(data)
                msg2 = data[data.find(":")+1:]
                message = msg + msg2

                print(message)


                try:
                    if message.find("infosec") >= 0:
                        raise smtplib.SMTPException

                    if message.find("bad word") >= 0:
                        raise smtplib.SMTPException

                    smtpObj = smtplib.SMTP('localhost')
                    smtpObj.sendmail(sender, receivers, message)
                    print("Successfully sent email")
                    data = "Successfully sent email"
                    connection.sendall(data.encode())
                except smtplib.SMTPException:
                    data = "Error: unable to send email"
                    connection.sendall(data.encode())




            if data[:5] == 'inbox':
                data = connection.recv(4096).decode('utf-8')
                HOST = 'localhost'
                USERNAME = username
                PASSWORD = password
                ssl = False

                server = IMAPClient(HOST, use_uid=True, ssl=ssl)
                server.login(USERNAME, PASSWORD)

                select_info = server.select_folder('INBOX')
                print('%d messages in INBOX' % select_info[b'EXISTS'])

                messages = server.search(['NOT', 'DELETED'])
                print("%d messages that aren't deleted" % len(messages))

                response = server.fetch(messages, ['BODY[TEXT]', 'ENVELOPE', 'FLAGS', 'RFC822'])

                print()
                print("Messages:")
                response = server.fetch(messages, ['BODY[TEXT]', 'ENVELOPE', 'FLAGS', 'RFC822.SIZE'])

                # ###
                # for msgid, data in response.items():
                #     print('Message ID: %d' % (msgid))
                #     print('Message Flags: %s' % (data[b'FLAGS']))
                #     print('Message Subject: %s' % (data[b'ENVELOPE'].subject))
                #     print('Message Data: %s' % (data[b'BODY[TEXT]']))
                # ###

                res=''
                for msgid, data in response.items():
                    data1='Message ID: %d' % (msgid)+'\n'
                    data3='Message Flags: %s' % (data[b'FLAGS'])+'\n'
                    data4='Message Subject: %s' % (data[b'ENVELOPE'].subject)+'\n'
                    data5='Message Data: %s' % (data[b'BODY[TEXT]'])

                    data6=data1+data3+data4+data5+'\n'
                    print("data666", data6)
                    #data6=data6+'\n'
                    data=res+data6
                    res=data
                    #data=data+'\n'
                    print("datainnn", data)

                ###
                print("dataaaa", res)
                data=res

                # for msgid, data in response.iteritems():
                #     print('   ID %d: %d bytes, flags=%s' % (msgid,
                #                                             data[b'RFC822.SIZE'],
                #                                             data[b'FLAGS'],
                #                                              ))

                # for msgid, data in response.items():
                #     data1 = "Message ID: "+str(msgid)+"Message Flags: "+str(data['FLAGS'])+"Message Subject: "+str(data['ENVELOPE'].subject)+"Message Data: "+str(data['BODY[TEXT]'])
                #     print("data1", data1)
                #     data2 =str(data)+str(data1)
                #     print("data2", data2)
                #     #connection.sendall(data.encode())
                #     #print(data1)
                # print("data2ff", data2)

                #data = "inbox!!!"
                connection.sendall(data.encode())



                #print(data)
                #connection.sendall(data.encode())





        # Receive the data in small chunks and retransmit it
        data = connection.recv(4096)
        #print('Server: Thread {}: received "{}"'.format(threads_count, data))
        connection.sendall(data)
    finally:
        connection.close()
        print('Server: Thread {}: finished'.format(threads_count))


while True:
    # Wait for a connection
    print('Server: waiting for a connection')
    connection, client_address = sock.accept()
    Thread(target=response, args=(connection,)).start()

这是一个完整的错误

Exception in thread Thread-1:
Server: Thread 1: finished
Traceback (most recent call last):
  File "C:\Python33\lib\threading.py", line 639, in _bootstrap_inner
    self.run()
  File "C:\Python33\lib\threading.py", line 596, in run
    self._target(*self._args, **self._kwargs)
  File "C:/Users/zeinab/PycharmProjects/untitled4/server.py", line 85, in response
    server = IMAPClient(HOST, use_uid=True, ssl=ssl)
  File "C:\Python33\lib\site-packages\imapclient\imapclient.py", line 152, in __init__
    self._imap = self._create_IMAP4()
  File "C:\Python33\lib\site-packages\imapclient\imapclient.py", line 166, in _create_IMAP4
    return imap4.IMAP4WithTimeout(self.host, self.port, self._timeout)
  File "C:\Python33\lib\site-packages\imapclient\imap4.py", line 13, in __init__
    imaplib.IMAP4.__init__(self, address, port)
  File "C:\Python33\lib\imaplib.py", line 173, in __init__
    self._connect()
  File "C:\Python33\lib\imaplib.py", line 202, in _connect
    self.welcome = self._get_response()
  File "C:\Python33\lib\imaplib.py", line 969, in _get_response
    resp = self._get_line()
  File "C:\Python33\lib\imaplib.py", line 1068, in _get_line
    raise self.abort('socket error: EOF')
imaplib.abort: socket error: EOF

0 个答案:

没有答案