socket operation timed out python

a marqué ce sujet comme résolu.

bonjour j’ai un serveur de chat en python

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
"""
Main program of the software, run a server on a given host and port
use sqlite3 to manage SQL interactions with database (connection, registration)
 """
# required modules
import socket  # creating the socket instance and run the server
import select  # for server interaction operation management
import threading  # accelerating the process
import datetime  # data informations
import sys  # to manage outputs of the program
import Crypto.Cipher  # to encrypt data and decrypt it while sending and receiving data
import sqlite3  # for sql database interactions
import time  # for analyzing time token by sql queries processes

# colors for different kinds of data
BLUE = '\033[94m'
GREEN = '\033[92m'
RED = '\033[1;31m'

# variables harvesting using sys.argv
if len(sys.argv) < 3:
    print(RED + '[usage] python server.py <hostname> <port>')
    sys.exit()
_HOST = sys.argv[1]
_PORT = int(sys.argv[2])

# main variables
_BUFFER = 4096
_RUN = True
_MAX = 10
_USERS = []

# product signature
print("            .___                            .__  .__                \n"
      "_____     __| _/______   ____   ____ _____  |  | |__| ____ ________ \n"
      "\__  \   / __ |\_  __ \_/ __ \ /    \\__  \ |  | |  |/    \\___   / \n"
      " / __ \_/ /_/ | |  | \/\  ___/|   |  \/ __ \|  |_|  |   |  \/    /  \n"
      "(____  /\____ | |__|    \___  >___|  (____  /____/__|___|  /_____ \ \n"
      "     \/      \/             \/     \/     \/             \/      \/ \n"
      "created by Gh0sT / ADZ team / contact me at ghost.adz@gmail.com / v1.0\n")


class Sql:
    def __init__(self):
        self.conn = sqlite3.connect('ADZ-database')
        self.cursor = self.conn.cursor()

    def inscription(self, username, password, requester):
        """
        this method dumps into the ADZ database username and password of the user (requester)
         :param username:
         :param password:
         :param requester:
        """
        try:
            self.cursor.execute('CREATE IF NOT EXISTS TABLE '
                                'users(username TEXT NOT NULL UNIQUE, password TEXT NOT NULL)')
            try:
                self.cursor.execute('INSERT INTO users(username, password)', (username, password))
                self.conn.commit()
                self.cursor.close()
                self.conn.close()
                print(GREEN + 'user[' + requester + '] created a new account\n')
                return 'executed'
            except sqlite3.IntegrityError:
                print(RED + 'user[' + requester + '] tried to create an account but username already exist...\n')
                return 'error-2'
        except sqlite3.Error:
            print(RED + 'An error occurred during creating a new account for the user: [' + requester + ']\n')
            return 'error-1'

    def connection(self, username, password, requester):
        """
        check if the data of the users are already registered in the database and allows or not the access
        :param username:
        :param password:
        :param requester:
        """
        try:
            self.cursor.execute('SELECT * FROM users WHERE username=? AND password=?', (username, password))
            data = self.cursor.fetchall()[0]
            if username == data[0] and password == data[1]:
                print(GREEN + 'user[' + username + '] entered the chatroom\n')
                return 'executed'
            else:
                print(RED + 'user[' + requester + '] failed the login...\n')
                return 'error-2'
        except sqlite3.Error:
            print(RED + 'An error occurred during the login process for the user: [' + requester + ']\n')
            return 'error-1'

Query = Sql()


class Server:
    def __init__(self):
        self.host = _HOST
        self.port = _PORT
        self.buff = _BUFFER
        self.users = _USERS
        self.run = _RUN
        self.conn = _MAX
        self.keys = {}

    def _bind(self):
        """
        create, set up and bind the server to listen any incoming connection
        """
        self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.server_socket.setblocking(False)
        self.server_socket.bind((self.host, self.port))
        self.server_socket.listen(self.conn)
        self.users.append(self.server_socket)
        print(BLUE + '---------- ADZ - chat server - gh0sT ----------\n')

    def _stop(self):
        """
        kill the server
        """
        self.run = False
        self.server_socket.close()

    def _send_data(self, sock, data):
        """
        encode and send data to all connected users except the server and the sender
        """
        for sockp in self.users:
            if sockp != self.server_socket and sockp != sock:
                try:
                    sockp.send(data.encode())
                except socket.error:
                    sockp.close()
                    self.users.remove(sock)

    def _send_one(self, sock, data):
        """
        encode and send data to only one user (used for sqlite query communications

        """
        for sockp in self.users:
            if sockp == sock:
                try:
                    sockp.send(data.encode())
                except socket.error:
                    sockp.close()
                    self.users.remove(sock)

    def _run(self):
        """
        run the server in a while loop
        """
        while self.run:
            try:
                ready_to_read, ready_to_write, in_error = select.select(self.users, [], [], 60)
            except socket.error:
                continue
            else:
                for sock in ready_to_read:
                    if sock == self.server_socket:
                        try:
                            # new client connection
                            client_socket, client_address = self.server_socket.accept()
                        except socket.error:
                            break
                        else:
                            self.users.append(client_socket)

                    else:
                        try:
                            data = sock.recv(self.buff)
                            if data:
                                spliter = data.split()

                                if spliter[0] == '/i':  # register.py target
                                    user = spliter[1]  # data harvesting
                                    password = spliter[2]  # data harvesting
                                    register = Query.inscription(user, password, sock)  # verify the statement returned
                                    if register == 'executed':  # statement verified
                                        self._send_one(sock, '/a your account has been created successfully!\n')
                                    else:
                                        self._send_one(sock, 'denied \n')

                                if spliter[0] == '/c':  # client.py target
                                    user = spliter[1]  # data harvesting
                                    password = spliter[2]  # data harvesting
                                    connection = Query.connection(user, password, sock)  # verify the statement returned
                                    if connection == 'executed':  # statement verified
                                        self.keys[client_address] = user  # dictionary for lines 200 - 206
                                        self._send_one(sock, 'executed\n')
                                        print(GREEN + '[{0}] entered the chat-room\n'.format(user))
                                    else:
                                        self._send_one(sock, 'denied\n')

                                if spliter[0] == '/q':  # right way to disconnect from the server
                                    user = spliter[1]  # data harvesting
                                    print(BLUE + 'user[' + sock + '] is offline (' + user + ')\n')
                                    self._send_data(sock, 'user[' + user + '] is offline\n')

                                print(GREEN + data)
                                self._send_data(sock, '\r' + data)

                        except socket.error:
                            self._send_data(sock, '\n user[{0}] is offline\n'.format(self.keys[client_address]))
                            print(RED + '\n user[{0}] is offline\n'.format(self.keys[client_address]))
                            sock.close()
                            self.users.remove(sock)
                            continue

        self._stop()

    def main(self):
        """
        main function that run the server with the set up
        :return:
        """
        self._bind()
        self._run()

if __name__ == '__main__':
    server = Server()
    server.main()

`

et un petit script pour que le cliuent s’enregistre dans la bdd grace a des messages a prefixes:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
"""
register program, same of the client but used just to communicate
with the server new account datas
"""

import socket
import select
import sys
import hashlib
import time

BLUE = '\033[94m'
GREEN = '\033[92m'
RED = '\033[1;31m'

print("            .___                            .__  .__                \n"
      "_____     __| _/______   ____   ____ _____  |  | |__| ____ ________ \n"
      "\__  \   / __ |\_  __ \_/ __ \ /    \\__  \ |  | |  |/    \\___   / \n"
      " / __ \_/ /_/ | |  | \/\  ___/|   |  \/ __ \|  |_|  |   |  \/    /  \n"
      "(____  /\____ | |__|    \___  >___|  (____  /____/__|___|  /_____ \ \n"
      "     \/      \/             \/     \/     \/             \/      \/ \n"
      "created by Gh0sT / ADZ team / contact me at ghost.adz@gmail.com / v1.0\n")

if len(sys.argv) < 3:
    print(RED + '[usage] python register.py <username> <password>\n')
    sys.exit()

username = sys.argv[1]
password = hashlib.md5(sys.argv[2].encode()).hexdigest()


class Register:
    def __init__(self):
        self.username = username
        self.password = password
        self.host = '192.168.1.22'
        self.port = 4567

    def _conn(self):
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.sock.settimeout(2)
        self.sock.connect((self.host, self.port))

    def _run(self):

        self._conn()

        print(GREEN + '[statement] connection to ADZ servers established...\n')
        start = time.time()
        run = True

        while run:
            rlist = [sys.stdin, self.sock]

            read_list, write_list, error_list = select.select(rlist, [], [])

            for sock in read_list:
                if sock == self.sock:
                    data = self.sock.recv(4096).decode()
                    split = data.split()
                    if split[0] == '/a':
                        print(GREEN + 'your account has been created successfully !\n')
                        end = time.time()
                        timer = end - start
                        timer = str(round(timer, 2))
                        print('[time] operation lasted: ' + timer)
                        sys.exit()
                    elif split[0] == 'denied':
                        print(RED + '[error 2] username already exists, please choose another one...\n')
                        sys.exit()
                    if not data:
                        print('[error 3] connection error, disconnected from ADZ servers...\n')


if __name__ == '__main__':
    register = Register()
    register._run()

la structure est semblable a celle d’un client, mais quand je run le register.py et bien voici la sortie après quelques seocndes:

1
2
3
4
elf.sock.connect((self.host, self.port))
socket.timeout: timed out

Process finished with exit code 1

le problème doit être au niveau de la connection au serveur mais j’ai regardé beaucoup de forum mais rien… pouvez vous m’éclairer s’il vous plait ? et sur ce joyeuses faites de noel a tous !

Connectez-vous pour pouvoir poster un message.
Connexion

Pas encore membre ?

Créez un compte en une minute pour profiter pleinement de toutes les fonctionnalités de Zeste de Savoir. Ici, tout est gratuit et sans publicité.
Créer un compte