I am new at python and I want to make a server-client application but every time I am attempting a connection I see this error.
I have tried changing sequency of send() and receive() functions but that didn't worked out
msg = client_socket.recv (BUFSIZ) .decode ("utf8")
OSError: [WinError 10038] An attempt was made to perform an operation on an object that is not a socket
Here is the code
Client.py
"""Handles receiving of messages."""
#client_socket.bind((HOST, PORT))
#client_socket.connect((HOST, PORT))
msg = client_socket.recv(BUFSIZ).decode("utf8")
print(msg)
client_socket.close()
def send(event=None): # event is passed by binders.
"""Handles sending of messages."""
client_socket.connect((HOST, PORT))
msg = input("MSG: ")
client_socket.send(bytes(msg, "utf8"))
client_socket.close()
#----Now comes the sockets part----
HOST = '127.0.0.1'
PORT = 7557
if not PORT:
PORT = 33000
else:
PORT = int(PORT)
BUFSIZ = 1024
ADDR = (HOST, PORT)
client_socket = socket(AF_INET, SOCK_STREAM)
client_socket.connect(ADDR)
receive_thread = Thread(target=receive)
receive_thread.start()
if __name__ == '__main__':
client_socket.close()
receive()
send()
receive()
Ps: 99% of code is from internet
Don't close your socket after receiving and sending information.
from socket import AF_INET, socket, SOCK_STREAM
from threading import Thread
def receive() :
"""Handles receiving of messages."""
while True :
msg = client_socket.recv(BUFSIZ).decode("utf8")
print(msg)
def send():
"""Handles sending of messages."""
while True:
msg = input("MSG: ")
client_socket.send(bytes(msg, "utf8"))
#----Now comes the sockets part----
HOST = '127.0.0.1'
PORT = 7557
BUFSIZ = 1024
ADDR = (HOST, PORT)
client_socket = socket(AF_INET, SOCK_STREAM)
client_socket.connect(ADDR)
receive_thread = Thread(target=receive, args=() )
send_thread = Thread(target=send, args=())
if __name__ == '__main__':
receive_thread.start()
send_thread.start()
This is a modified version of your code.
I made a similar application by myself using the same logic, take a look:
https://github.com/moe-assal/Chatting_Server
Related
Problem: My server application only accepts one connection at a time. I'd like to know why serverSocket.listen() doesn't listen and serverSocket.accept() doesn't accept all connections.
import socket
SERVER_ADDRESSES = ['0.0.0.0']
SERVER_PORT = 8091
CONNECTED_CLIENTS = {}
def processClientConnection(clientSocket, clientAddress):
while True:
try:
print("Listening for messages...")
message = clientSocket.recv(1024)
message = message.decode("UTF-8")
for client in CONNECTED_CLIENTS.keys():
print(f"{CONNECTED_CLIENTS[client]} vs {clientAddress}")
print(CONNECTED_CLIENTS[client] == clientAddress)
if CONNECTED_CLIENTS[client] != clientAddress:
print(f"Sending message to {CONNECTED_CLIENTS[client]}")
client.send(b"%s: %s" % (CONNECTED_CLIENTS[client][0], message))
except ConnectionResetError:
print(f"{CONNECTED_CLIENTS[clientSocket][0]} disconnected!")
for client in CONNECTED_CLIENTS.keys():
if clientSocket != client:
client.send(b"%s disconnected!" % CONNECTED_CLIENTS[clientSocket][0])
del(CONNECTED_CLIENTS[clientSocket])
def startServer(serverAddress):
serverSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print(f"Socket Host Name: {serverAddress}:{SERVER_PORT}")
serverSocket.bind((serverAddress, 8091))
# become a server socket
while True:
print("Listening for connections")
serverSocket.listen()
(clientSocket, address) = serverSocket.accept()
if (clientSocket, address) in CONNECTED_CLIENTS:
print("Can't connect multiple of same client")
break
CONNECTED_CLIENTS[clientSocket] = address
print(f"{CONNECTED_CLIENTS[clientSocket][0]} connected!")
ct = threading.Thread(target=processClientConnection, args=([clientSocket, address]))
ct.run()
def runServer():
for serverAddress in SERVER_ADDRESSES:
serverThread = threading.Thread(target=startServer, args=([serverAddress]))
serverThread.start()
if __name__ == '__main__':
print('Server Started')
runServer()
import socket
SERVER_ADDRESS = '127.0.0.1'
SERVER_PORT = 8091
def receiveMessage(sock):
while True:
try:
message = sock.recv(1024).decode("UTF-8")
if len(message):
print(message)
except ConnectionResetError:
print("Server disconnected you")
sock.close()
exit(0)
except ConnectionAbortedError:
print("Server disconnected you")
sock.close()
exit(0)
def sendMessage(sock):
while True:
try:
message = input()
sock.send(bytes(message, "UTF-8"))
except ConnectionResetError:
print("Server disconnected you")
sock.close()
exit(0)
except ConnectionAbortedError:
print("Server disconnected you")
sock.close()
exit(0)
except EOFError:
print("Client closed")
sock.close()
exit(0)
def runClient():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
s.connect((SERVER_ADDRESS, SERVER_PORT))
except TimeoutError:
print("Server down")
s.close()
exit(0)
except ConnectionRefusedError:
print("Server down")
s.close()
exit(0)
print("Connected to server. Type your message.\n")
messagingThread = threading.Thread(target=sendMessage, args=([s]))
messagingThread.start()
receivingThread = threading.Thread(target=receiveMessage, args=([s]))
receivingThread.start()
if __name__ == '__main__':
print("Client started")
runClient()
while True:
print("Listening for connections")
serverSocket.listen()
(clientSocket, address) = serverSocket.accept()
...
ct = threading.Thread(target=processClientConnection, args=([clientSocket, address]))
ct.run()
This is wrong in multiple ways:
A server socket should be created once, should be bound once to the address and should call listen once in order to setup the listen queue. After that accept should be called again and again to get the newly established connections. You instead create it once, bind it once but then call listen again and again.
You are attempting to create a new thread for each new connection in order to handle the new client connection in parallel to the other activity. But since you use ct.run() instead of ct.start() the thread function will be called directly within the current thread and not in parallel to the existing one. This means new connections will only be accepted once the code is done with the current one.
I am trying to make it so multiple clients can connect to my server and communicate with each other. At the moment I load up the server and connect the client and I can send messages to the server I can also connect another client but when i send messages from a client i want it to go to the other client so they can see it. At the moment all it does is send it to the server can anyone help. Here is my code so far:
import socket
import threading
import select
import time
from queue import Queue
all_connections = []
all_address = []
HEADER = 64
PORT = 5050
SERVER = socket.gethostbyname(socket.gethostname())
ADDR = (SERVER, PORT)
FORMAT = 'utf-8'
DISCONNECT_MESSAGE = '!DISCONNECT'
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(ADDR)
def handle_client(conn, addr,):
print(f'[NEW CONNECTION] {addr} connected.')
connected = True
while connected:
msg_length = conn.recv(HEADER).decode(FORMAT)
if msg_length:
msg_length = int(msg_length)
msg = conn.recv(msg_length).decode(FORMAT)
if '[SERVER]' in msg:
print('')
else:
print(f'[{addr}] {msg}')
if msg == DISCONNECT_MESSAGE:
connected = False
print(f'[{addr}] has disconnected')
conn.close()
def start():
server.listen()
print(f'[LISTENING] Server is listening on {SERVER}')
while True:
conn, addr = server.accept()
conn.send("Welcome to server!".encode(FORMAT))
thread = threading.Thread(target=handle_client, args=(conn, addr))
thread.start()
print(f'[ACTIVE CONNECTIONS] {threading.activeCount() -1}')
print('[STARTING] server is starting...')
start()
I'm trying to connect 2 remote computers at different locations.
Everytime i added my public IP address in the parameter, an error is thrown.
OSError: [WinError 10049] The requested address is not valid in its context
This is the server side code i used in this project:
import socket
import threading
HEADER = 64
PORT = 5050
SERVER = **PUBLIC IP**
ADDR = (SERVER, PORT)
FORMAT = 'utf-8'
DISCONNECT_MESSAGE = "!DISCONNECT"
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(ADDR)
def handle_client(conn, addr):
print(f"[NEW CONNECTION] {addr} connected.")
connected = True
while connected:
msg_length = conn.recv(HEADER).decode(FORMAT)
if msg_length:
msg_length = int(msg_length)
msg = conn.recv(msg_length).decode(FORMAT)
if msg == DISCONNECT_MESSAGE:
connected = False
print(f"[{addr}] {msg}")
conn.send("Msg received".encode(FORMAT))
conn.close()
def start():
server.listen()
print(f"[LISTENING] Server is listening on {SERVER}")
while True:
conn, addr = server.accept()
thread = threading.Thread(target=handle_client, args=(conn, addr))
thread.start()
print(f"[ACTIVE CONNECTIONS] {threading.activeCount() - 1}")
print("[STARTING] server is starting...")
start()
Set SERVER = '0.0.0.0' to bind to the server's IP.
I am trying to set up a server that can send each client - commands.
One command is 'lock' which locks the screen of the client.
When a client gets the word "lock" it runs this code on the client:
import ctypes
ctypes.windll.user32.LockWorkStation()
This code does lock the screen however- it ends my connection with the client..
How can I make the client stay connected but still locked?
Note: The locking is not forever! it is only once, like putting the client's computer in sleep mode until he wants to unlock the screen.
Hope I was clear enough. Thanks for helping!
Server:
import socket
def main():
sock = socket.socket()
sock.bind(('0.0.0.0', 4582))
print("Waiting for connections...")
sock.listen(1)
conn, addr = sock.accept()
print ("New connection from: ", addr)
while 1:
command = input("Enter command> ")
if command == 'shutdown':
sock.send(b'shutdown')
elif command == 'lock':
sock.send(b'lock')
else:
print ("Unknown command")
data = sock.recv(1024)
print (data)
if __name__ == '__main__':
main()
Client:
import socket
import ctypes
def main():
sock = socket.socket()
sock.connect(('127.0.0.1', 4582))
while 1:
data = sock.recv(1024)
print (data)
if data == 'lock':
sock.send(b'locking')
ctypes.windll.user32.LockWorkStation()
sock.recv(1024)
if __name__ == '__main__':
main()
I adapted the example from the Python docs to your needs.
Example for server.py:
import socket
HOST = '127.0.0.1'
PORT = 4582
with socket.socket() as s:
print('Waiting for connection...')
s.bind((HOST, PORT))
s.listen(1)
conn, addr = s.accept()
with conn:
print('Connected by', addr)
while True:
data = input('Which command? ')
if data in ['lock', 'shutdown']:
conn.send(data.encode())
else:
print('Command unknown')
Example for client.py:
import ctypes
import socket
HOST = '127.0.0.1'
PORT = 4582
with socket.socket() as s:
s.connect((HOST, PORT))
while True:
data = s.recv(1024).decode()
if not data:
print('Server disconnected')
break
print('Received command:', data)
if data == 'shutdown':
print('Shutting down client...')
break
if data == 'lock':
print('Locking...')
ctypes.windll.user32.LockWorkStation()
I am a total beginner in Python and today I tried to create a simple chat-program. So far it doesn't work too bad, but I am unable to communicate between the server and the client. I can only send from the server to the client but not in the other direction. I tried it with multithreading and these are the results:
Server:
import socket
import threading
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = "127.0.0.1"
port = 4444
s.bind((host, port))
s.listen(3)
conn, addr = s.accept()
print("Connection from: "+str(addr[0])+":"+str(addr[1]))
def recv_data():
while True:
data = s.recv(2048).decode('utf-8')
print(data)
def send_data():
while True:
msg = input(str(socket.gethostname())+"> ")
msg = str(host + "> ").encode('utf-8') + msg.encode('utf-8')
conn.send(msg)
#t1 = threading.Thread(target=recv_data)
t2 = threading.Thread(target=send_data)
#t1.start()
t2.start()
Client:
import socket
import threading
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = "127.0.0.1"
port = 4444
s.connect((host, port))
print("Connected to: "+ host)
def recv_data():
while True:
data = s.recv(2048)
data = data.decode('utf-8')
print(data)
def send_data():
while True:
msg = input(str(host)+"> ").encode('utf-8')
s.send(msg)
t1 = threading.Thread(target=recv_data)
#t2 = threading.Thread(target=send_data)
t1.start()
#t2.start()
This code works; the server can send, the client receive, but whenever I uncomment the second thread, so that it can do both I get an error:
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
I can't seem to find a solution, so please help, what am I doing wrong? :D
conn, addr = s.accept()
def recv_data():
while True:
data = s.recv(2048).decode('utf-8')
print(data)
conn is actually the socket you want to send or recv. The error occurs because you are trying to recv from the server socket, which is illegal action. Therefore you need to change s to conn if you want to make it work.