1

I've just finish coding my chat application using socket import on python and i came across with a error "OSError: [WinError 10038] An operation was attempted on something that is not a socket"

I never came across this error and I don't know what to do

in previous codes that was almost exactly like this one an error from this kind never popped up

can someone help me out, it will be much appreciated.

thank you

-itay

import threading
import socket


#server code


#HOST = '127.0.0.1'
HOST = '0.0.0.0'
PORT = 4434

server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((HOST, PORT))

server.listen()

clients = []
nicknames = []


def broadcast(message):
    for client in clients:
        client.send(message)


def handle(client):
    while True:
        try:
            msg = message = client.recv(1024)


            if msg.decode('ascii').startswith('KICK'):

                # if nicknames[clients.index(client)] == 'admin': should fix
                nameToKick = msg.decode('ascii')[5:]
                kickUser(nameToKick)
                # else:
                #     client.send('command was refused'.encode('ascii')) should fix

            elif msg.decode('ascii').startswith('BAN'):

                # if nicknames[clients.index(client)] == 'admin': should fix
                nameToBan = msg.decode('ascii')[4:]
                kickUser(nameToBan)

                with open('bans.txt', 'a') as f:
                    f.write(f'{nameToBan}\n')

                print(f'{nameToBan} was banned from this server by an admin')

                # else:
                #     client.send('command was refused'.encode('ascii')) should fix

            else:
                broadcast(message)

        except:
                if client in clients:
                    index = clients.index(client)
                    clients.remove(client)
                    client.close()
                    nickname = nicknames[index]
                    broadcast(f'{nickname} left the chat'.encode('ascii'))
                    nicknames.remove(nickname)
                    break

def receive():
    while True:
        client, address = server.accept()
        print(f"conneted with {str(address)}")
        client.send('NICK'.encode('ascii'))
        nickname = client.recv(1024).decode('ascii')

        with open('bans.txt', 'r') as f:
            bans = f.readlines()

        if nickname + '\n' in bans:
            client.send('BAN'.encode('ascii'))
            client.close()
            continue

        if nickname == 'admin':
            client.send("PASS".encode('ascii'))
            password = client.recv(1024).decode('ascii')
            if password != "12345":
                client.send('REFUSE'.encode('ascii'))
                client.close()
                continue

        nicknames.append(nickname)
        clients.append(client)

        print(f"nickname : {nickname}")
        broadcast(f"{nickname} joined".encode('ascii'))
        client.send('Connected to the server'.encode('ascii'))

        thread = threading.Thread(target=handle, args=(client,))
        thread.start()


def kickUser(name):
    if name in nicknames:
        name_index = nicknames.index(name)
        clientToKick = clients[name_index]
        clients.remove(clientToKick)
        clientToKick.send("You were kicked by an admin".encode('ascii'))
        clientToKick.close()
        nicknames.remove(name)
        broadcast(f'{name} was kicked by admin'.encode('ascii'))


print("server is listening ... ")
receive()
import threading
import socket


#client code

#HOST = '127.0.0.1'
HOST = '192.168.100.14'
PORT = 4434

stop_thread = False

nickname = input("Enter a nickname : ")
if nickname == 'admin':
    password = input("Enter password for admin :")

client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect((HOST, PORT))

def receive():
    while True:

        global stop_thread
        if stop_thread:
            break

        try:
            message = client.recv(1024).decode('ascii')

            if message == "NICK":
                client.send(nickname.encode('ascii'))
                next_message = client.recv(1024).decode('ascii')

                if next_message == 'PASS':
                    client.send(password.encode('ascii'))
                    if client.recv(1024).decode('ascii') == 'REFUSE':
                        print("Connection refused wrong password")
                        stop_thread = True

                elif next_message == 'BAN':
                    print("Connection refused, you are banned from this server!")
                    client.close()
                    stop_thread = True

            else:
                print(message)

        except:
            print("error occurred")
            client.close()
            break



def write():
    global client
    while True:

        if stop_thread:
            break
        # type quit() to quit the chat
        message = f'{nickname}: {input("")}'
        if message[len(nickname) + 2:] == 'quit()':
            print(f'{nickname} left!')
            client.close()



        elif message[len(nickname) + 2:].startswith('/'):

            if nickname == 'admin':

                if message[len(nickname) + 2:].startswith('/kick'):
                    client.send(f'KICK {message[len(nickname) + 2 + 6:]}'.encode('ascii'))

                elif message[len(nickname) + 2:].startswith('/ban'):
                    client.send(f'BAN {message[len(nickname) + 2 + 5:]}'.encode('ascii'))

                elif message[len(nickname) + 2:].startswith('/unban'):
                    client.send(f'UNBAN {message[len(nickname) + 2 + 5:]}'.encode('ascii'))
            else:
                print("commands can only be executed by the admin")

        else:
            client.send(message.encode('ascii'))


#threads to establish more than 1 connection at a time
receiveThread = threading.Thread(target=receive)
receiveThread.start()

writeThread = threading.Thread(target=write)
writeThread.start()
itay
  • 11
  • 1
  • 1
    There's 100 lines of code here. WHICH ONE gets the error? – Tim Roberts Jun 15 '22 at 05:37
  • I'm sorry, the else at the end of the write function (else send(client.send(message.encode('ascii')) – itay Jun 15 '22 at 05:56
  • 1
    If ANY of those paths in either function close the socket, the `client.send` will fail. – Tim Roberts Jun 15 '22 at 06:19
  • So far every question I read today tagged with python and sockets has gotten this fundamental fact about stream sockets wrong. This is what happens when code is copied and pasted but not understood. Please read https://stackoverflow.com/a/43420503/238704 – President James K. Polk Jun 15 '22 at 13:34

0 Answers0