#πŸ”’ i have a problem with sockets

79 messages Β· Page 1 of 1 (latest)

copper viper
#

if anyone knows how to fix please help client.py--
#client
#dictionary + json file + messaging text file
import json
import os

import socket
import threading

users = [] # delete and all the file info
loggedin = False
current_account = None

server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

try:
server.connect(("127.0.0.1", 55555))
print("Connected to the server")
except socket.error as e:
print(f"Failed to connect to the server: {e}")
exit(1)

def receive():
global server
global users
while True:
try:
message = server.recv(1024)
if not message:
print("there is no message!")
else:
message = message.decode("ascii")
message = json.loads(message)
print(message)
if isinstance(message, list) and len(message) > 1 and message[0] == "data":
users = message[1]
except socket.error as e:
print(f"an error occured(1): {e}")
server.close()
break
def write():
global server
while True:
try:
message = ["data",users]
if message:
message = json.dumps(message)
server.send(message.encode("ascii"))
except socket.error as e:
print(f"an error occured(2): {e}")
server.close()
break
receive_thread = threading.Thread(target=receive)
receive_thread.start()

write_thread = threading.Thread(target=write)
write_thread.start()
(relevant code)

summer ploverBOT
#

@copper viper

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

copper viper
#

-server.py
import threading
import socket
import json
import os

host = "127.0.0.1" # local host
port = 55555

server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # socket
server.bind((host, port)) # start hosting
server.listen() # allows connections
clients = []
users = []

def load():
global users,clients
if os.path.getsize("user_info.json") > 0:
with open("user_info.json", "r") as json_file:
users = json.load(json_file)

def handle(client):
global clients
while True:
try:
message = ["data",users]
print(message)
message = json.dumps(message).encode("ascii")
print(message)
server.send(message)
except Exception as e:
print(f"closed(1) {e}")
clients.remove(client)
client.close()
break

def get(client):
global users
while True:
try:
message = client.recv(1024).decode("ascii")
if message:
message = json.loads(message)
if message[0] == "data":
users = message[1]
except:
print("closed")
clients.remove(client)
client.close()
break

def receive():
global clients
while True:
client, address = server.accept() # waits for a connection
print(f"Connected with {str(address)}")
clients.append(client)
print(client)
print(clients)
thread = threading.Thread(target=handle, args=(client,))
thread.start()

    thread2 = threading.Thread(target=get, args=(client,))
    thread2.start()

print("server is listening")
receive()

summer ploverBOT
#

Hey @copper viper!

It looks like you're trying to paste code into this channel.

Discord has support for Markdown, which allows you to post code with full syntax highlighting. Please use these whenever you paste code, as this helps improve the legibility and makes it easier for us to help you.

To do this, use the following method:
```py
print('Hello, world!')
```

This will result in the following:

print('Hello, world!')```
You can **edit your original message** to correct your code block.
copper viper
#

error message:Exception in thread Thread-1 (handle):
Traceback (most recent call last):
File "C:\Users\PC\Downloads\messaging_ap(no_gui)\server.py", line 29, in handle
server.sendall(message)
OSError: [WinError 10057] A request to send or receive data was disallowed because the socket is not connected and (when sending on a datagram socket using a sendto call) no address was supplied

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "C:\Users\PC\AppData\Local\Programs\Python\Python312\Lib\threading.py", line 1073, in _bootstrap_inner
self.run()
File "C:\Users\PC\AppData\Local\Programs\Python\Python312\Lib\threading.py", line 1010, in run
self._target(*self._args, **self._kwargs)
File "C:\Users\PC\Downloads\messaging_ap(no_gui)\server.py", line 32, in handle
clients.remove(client)
ValueError: list.remove(x): x not in list

#

its meant to be a messaging system with sockets but for some reason it throws exceptions whenever i try to send data

opaque kelp
#

!code

summer ploverBOT
#
Formatting code on Discord

Here's how to format Python code on Discord:

```py
print('Hello world!')
```

These are backticks, not quotes. Check this out if you can't find the backtick key.

For long code samples, you can use our pastebin.

opaque kelp
#

Please format the code.

copper viper
#

?

#

oh right

opaque kelp
#

!code

summer ploverBOT
#
Formatting code on Discord

Here's how to format Python code on Discord:

```py
print('Hello world!')
```

These are backticks, not quotes. Check this out if you can't find the backtick key.

For long code samples, you can use our pastebin.

hot wing
#
like this
#

```py
like this
```

copper viper
#
import socket
import json
import os

host = "127.0.0.1" # local host
port = 55555

server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # socket
server.bind((host, port)) # start hosting
server.listen() # allows connections
clients = []
users = []

def load():
    global users,clients
    if os.path.getsize("user_info.json") > 0:
        with open("user_info.json", "r") as json_file:
            users = json.load(json_file)

def handle(client):
    global clients
    while True:
        try:
            message = ["data",users]
            print(message)
            message = json.dumps(message).encode("ascii") 
            print(message)
            server.send(message)
        except Exception as e:
            print(f"closed(1) {e}")
            clients.remove(client)
            client.close()
            break

def get(client):
    global users
    while True:
        try:
            message = client.recv(1024).decode("ascii")
            if message:
                message = json.loads(message)
                if message[0] == "data":
                    users = message[1]
        except:
            print("closed")
            clients.remove(client)
            client.close()
            break

def receive():
    global clients
    while True:
        client, address = server.accept() # waits for a connection
        print(f"Connected with {str(address)}")
        clients.append(client)
        print(client)
        print(clients)
        thread = threading.Thread(target=handle, args=(client,))
        thread.start()

        thread2 = threading.Thread(target=get, args=(client,))
        thread2.start()
print("server is listening")
receive()
summer ploverBOT
#

Hey @copper viper!

It looks like you pasted Python code without syntax highlighting.

Please use syntax highlighting to improve the legibility of your code and make it easier for us to help you.

To do this, use the following method:
```py
print('Hello, world!')
```

This will result in the following:

print('Hello, world!')```
You can **edit your original message** to correct your code block.
hot wing
#

just add py after ```

copper viper
#
import threading
import socket
import json
import os

host = "127.0.0.1" # local host
port = 55555

server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # socket
server.bind((host, port)) # start hosting
server.listen() # allows connections
clients = []
users = []

def load():
    global users,clients
    if os.path.getsize("user_info.json") > 0:
        with open("user_info.json", "r") as json_file:
            users = json.load(json_file)

def handle(client):
    global clients
    while True:
        try:
            message = ["data",users]
            print(message)
            message = json.dumps(message).encode("ascii") 
            print(message)
            server.send(message)
        except Exception as e:
            print(f"closed(1) {e}")
            clients.remove(client)
            client.close()
            break

def get(client):
    global users
    while True:
        try:
            message = client.recv(1024).decode("ascii")
            if message:
                message = json.loads(message)
                if message[0] == "data":
                    users = message[1]
        except:
            print("closed")
            clients.remove(client)
            client.close()
            break

def receive():
    global clients
    while True:
        client, address = server.accept() # waits for a connection
        print(f"Connected with {str(address)}")
        clients.append(client)
        print(client)
        print(clients)
        thread = threading.Thread(target=handle, args=(client,))
        thread.start()

        thread2 = threading.Thread(target=get, args=(client,))
        thread2.start()
print("server is listening")
receive()
opaque kelp
#

Think about this line: server.send(message). Who are you sending to?

hot wing
#

(the formatting is/code block) perfect

copper viper
# opaque kelp Think about this line: `server.send(message)`. Who are you sending to?
#client
#dictionary + json file + messaging text file
import json
import os

import socket
import threading

users = [] # delete and all the file info
loggedin = False
current_account = None
  
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

try:
    server.connect(("127.0.0.1", 55555))
    print("Connected to the server")
except socket.error as e:
    print(f"Failed to connect to the server: {e}")
    exit(1)

def receive():
    global server
    global users
    while True:
        try:
            message = server.recv(1024)
            if not message:
                print("there is no message!")
            else:
                message = message.decode("ascii")
                message = json.loads(message)
                print(message)
                if isinstance(message, list) and len(message) > 1 and message[0] == "data":
                        users = message[1] 
        except socket.error as e:
            print(f"an error occured(1): {e}")
            server.close()
            break
def write():
    global server
    while True:
        try:    
            message = ["data",users]
            if message:
                message = json.dumps(message) 
                server.send(message.encode("ascii"))
        except socket.error as e:
            print(f"an error occured(2): {e}")
            server.close()
            break
receive_thread = threading.Thread(target=receive)
receive_thread.start()

write_thread = threading.Thread(target=write)
write_thread.start()```
#

the server

opaque kelp
#

That line is in the server code though.

copper viper
#

i mean i am sending to the client

#

its ment to send data as a list to the client

opaque kelp
#

But look at what socket you're calling send on.

copper viper
#

oooooh

#

wait

copper viper
opaque kelp
#

You're calling send on the server socket, from the server. What client will this be sent to?

#

How would it know?

#

If you have 10 clients connected, which would you expect it to be sent to?

copper viper
#

so i should do client.send instead right?

opaque kelp
#

Yes. You use the socket returned by accept to communicate with the other end.

copper viper
#

alright

#

but even with correct it :Exception in thread Thread-1 (handle):
Traceback (most recent call last):
File "C:\Users\PC\Downloads\messaging_ap(no_gui)\server.py", line 29, in handle
client.send(message)
OSError: [WinError 10038] An operation was attempted on something that is not a socket

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "C:\Users\PC\AppData\Local\Programs\Python\Python312\Lib\threading.py", line 1073, in _bootstrap_inner
self.run()
File "C:\Users\PC\AppData\Local\Programs\Python\Python312\Lib\threading.py", line 1010, in run
self._target(*self._args, **self._kwargs)
File "C:\Users\PC\Downloads\messaging_ap(no_gui)\server.py", line 32, in handle
clients.remove(client)
ValueError: list.remove(x): x not in list

#

def handle(client):
global clients
while True:
try:
message = ["data",users]
print(message)
message = json.dumps(message).encode("ascii")
print(message)
client.send(message)
except Exception as e:
print(f"closed(1) {e}")
clients.remove(client)
client.close()
break

summer ploverBOT
#

Hey @copper viper!

It looks like you're trying to paste code into this channel.

Discord has support for Markdown, which allows you to post code with full syntax highlighting. Please use these whenever you paste code, as this helps improve the legibility and makes it easier for us to help you.

To do this, use the following method:
```py
print('Hello, world!')
```

This will result in the following:

print('Hello, world!')```
You can **edit your original message** to correct your code block.
copper viper
#

def handle(client):
global clients
while True:
try:
message = ["data",users]
print(message)
message = json.dumps(message).encode("ascii")
print(message)
client.send(message)
except Exception as e:
print(f"closed(1) {e}")
clients.remove(client)
client.close()
break

opaque kelp
#

An operation was attempted on something that is not a socket
This typically means the socket has been closed already.

copper viper
#

oh

#

why?

opaque kelp
copper viper
#

its saying that the client.send the client isnt a socket

#

server is listening
Connected with ('127.0.0.1', 57230)
<socket.socket fd=280, family=2, type=1, proto=0, laddr=('127.0.0.1', 55555), raddr=('127.0.0.1', 57230)>
[<socket.socket fd=280, family=2, type=1, proto=0, laddr=('127.0.0.1', 55555), raddr=('127.0.0.1', 57230)>]
['data', []]closed

b'["data", []]'
closed(1) [WinError 10038] An operation was attempted on something that is not a socket

opaque kelp
#

closed

copper viper
#

?

opaque kelp
#

Note it says "closed" in the printout.

#

['data', []]closed

copper viper
#

oh so its because one of the threads already failed

opaque kelp
#

An error is being thrown in get apparently. You've discarded the error though, so we don't know what it is. Change the except block to

except Exception as e:
    print("Closed due to error:", e)

And run it again.

copper viper
#

server is listening
Connected with ('127.0.0.1', 57311)
<socket.socket fd=284, family=2, type=1, proto=0, laddr=('127.0.0.1', 55555), raddr=('127.0.0.1', 57311)>
[<socket.socket fd=284, family=2, type=1, proto=0, laddr=('127.0.0.1', 55555), raddr=('127.0.0.1', 57311)>]
['data', []]closed due to error: Extra data: line 1 column 13 (char 12)

b'["data", []]'
closed(1) [WinError 10038] An operation was attempted on something that is not a socket
Exception in thread Thread-1 (handle):
Traceback (most recent call last):
File "C:\Users\PC\Downloads\messaging_ap(no_gui)\server.py", line 29, in handle
client.send(message)
OSError: [WinError 10038] An operation was attempted on something that is not a socket

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "C:\Users\PC\AppData\Local\Programs\Python\Python312\Lib\threading.py", line 1073, in _bootstrap_inner
self.run()
File "C:\Users\PC\AppData\Local\Programs\Python\Python312\Lib\threading.py", line 1010, in run
self._target(*self._args, **self._kwargs)
File "C:\Users\PC\Downloads\messaging_ap(no_gui)\server.py", line 32, in handle
clients.remove(client)
ValueError: list.remove(x): x not in list

#

what does extra data mean?

opaque kelp
#

closed due to error: Extra data: line 1 column 13 (char 12)

copper viper
#

what does it mean

opaque kelp
#

It looks like the message isn't valid JSON. Print out message to verify what it is.

#

It could be just that you aren't getting the whole message. recv is not guaranteed to give you the entire message at once.

copper viper
#

oh

#

server is listening
Connected with ('127.0.0.1', 57343)
<socket.socket fd=356, family=2, type=1, proto=0, laddr=('127.0.0.1', 55555), raddr=('127.0.0.1', 57343)>
[<socket.socket fd=356, family=2, type=1, proto=0, laddr=('127.0.0.1', 55555), raddr=('127.0.0.1', 57343)>]
['data', []]message:["data", []]["data", []]["data", []]["data", []]["data", []]["data", []]["data", []]["data", []]["data", []]["data", []]["data", []]["data", []]["data", []]["data", []]["data", []]["data", []]["data", []]["data", []]["data", []]["data", []]["data", []]["data", []]["data", []]["data", []]["data", []]["data", []]["data", []]["data", []]["data", []]["data", []]["data", []]["data", []]["data", []]["data", []]["data", []]["data", []]["data", []]["data", []]["data", []]["data", []]["data", []]["data", []]["data", []]["data", []]["data", []]["data", []]["data", []]["data", []]["data", []]["data", []]["data", []]["data", []]["data", []]["data", []]["data", []]["data", []]["data", []]["data", []]["data", []]["data", []]["data", []]["data", []]["data", []]["data", []]["data", []]["data", []]["data", []]["data", []]["data", []]["data", []]["data", []]["data", []]["data", []]["data", []]["data", []]["data", []]["data", []]["data", []]["data", []]["data", []]["data", []]["data", []]["data", []]["data", []]["data", []]["da

#

b'["data", []]'closed due to error: Extra data: line 1 column 13 (char 12)

['data', []]
b'["data", []]'
closed(1) [WinError 10038] An operation was attempted on something that is not a socket
Exception in thread Thread-1 (handle):
Traceback (most recent call last):
File "C:\Users\PC\Downloads\messaging_ap(no_gui)\server.py", line 29, in handle
client.send(message)
OSError: [WinError 10038] An operation was attempted on something that is not a socket

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "C:\Users\PC\AppData\Local\Programs\Python\Python312\Lib\threading.py", line 1073, in _bootstrap_inner
self.run()
File "C:\Users\PC\AppData\Local\Programs\Python\Python312\Lib\threading.py", line 1010, in run
self._target(*self._args, **self._kwargs)
File "C:\Users\PC\Downloads\messaging_ap(no_gui)\server.py", line 32, in handle
clients.remove(client)
ValueError: list.remove(x): x not in list

#

thats weird

copper viper
#

oh

#

yea thats the non json bit

opaque kelp
#

["data", []]["data", []]["data", []] you can't have lists like this.

copper viper
#

def get(client):
global users
while True:
try:
message = client.recv(1024).decode("ascii")
print(f"message:{message}")
if message:
message = json.loads(message)
print(f"json message:{message}")
if message[0] == "data":
users = message[1]
except Exception as e:
print(f"closed due to error: {e}")
clients.remove(client)
client.close()
break

summer ploverBOT
#

Hey @copper viper!

It looks like you're trying to paste code into this channel.

Discord has support for Markdown, which allows you to post code with full syntax highlighting. Please use these whenever you paste code, as this helps improve the legibility and makes it easier for us to help you.

To do this, use the following method:
```py
print('Hello, world!')
```

This will result in the following:

print('Hello, world!')```
You can **edit your original message** to correct your code block.
copper viper
#

oh

#

why cant i have lists like that

opaque kelp
copper viper
#

oh

opaque kelp
#

I think the problem is your client's write function.

#

It looks like it's just spamming messages to the server as fast as it can.

copper viper
#

oh

opaque kelp
copper viper
#

thank you

summer ploverBOT
#
Python help channel closed

This help channel has been closed and it's no longer possible to send messages here. If your question wasn't answered, feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.