How to connect multiple socket servers in python? - python

So, I have a server script in python and a client script. I want to use multiple server machines to host a single server script.
Here is my server script:
import socket
import threading
HEADER = 64
PORT = 5050
SERVER = "0.0.0.0"#socket.gethostbyname(socket.gethostname())
ADDR = (SERVER, PORT)
FORMAT = 'utf-8'
DISCONNECT_MESSAGE = "!DISCONNECT"
clients = []
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
clients.append(conn)
while connected:
msg_length = conn.recv(HEADER).decode(FORMAT)
if msg_length:
msg_length = int(msg_length)
msg = conn.recv(msg_length).decode(FORMAT)
for items in clients:
items.send(msg.encode(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}")
if __name__ == "__main__":
print("[STARTING] server is starting...")
start()
so basically, I want to host this single script on multiple machines but they must have the same data like the client list should be same in all the machines and all the other variables.
Can someone please help me?

Related

Cannot send data to two clients at the same time when using sockets in python

I'm currently trying to make a socket server and client program in which the server is able to send simple strings of text to the clients. As of now even when two clients are recognized and established, the message only gets sent to whichever connected first. I've been moving around lots of my code and trying to solve the problem but nothing seems to work. My code for the server is immediately below followed by the client code. Everything works when I only connect to one client; however, as soon as a second connection is made and recognized it continues to only send to the first client while the second client stays in a waiting process. Any help is appreciated and thank you!
server code
import socket
import threading
import time
HEADER = 2048
PORT = 4444
SERVER = server ip (redacted)
ADDR = (SERVER, PORT)
FORMAT = 'utf-8'
DISCONNECT_MESSAGE = "dc"
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(ADDR)
def handle_client(conn, addr):
print(f"[NEW CONNECTION] {addr} connected.")
while True:
comman = input("message: ")
conn.send(comman.encode(FORMAT))
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("server is starting...")
start()
client code
import socket
from sys import stdin
import time
import subprocess
import os
HEADER = 2048
PORT = 4444
FORMAT = 'utf-8'
DISCONNECT_MESSAGE = "dc"
SERVER = server ip (redacted)
ADDR = (SERVER, PORT)
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(ADDR)
def recieve():
while True:
print(client.recv(2048).decode(FORMAT))
recieve()

Python sockets how to add multiple clients and send bytes to each client

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()

Python socket error thrown with IP addresses

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.

Python ConnectionRefusedError: [WinError 10061]

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

Python Socket connect two devices on same network

I am attempting to connect a simple server and client from two computers on the same network. Both the client and server cannot 'find' each other, as they do not move past .connect() and .accept() respectively. What am I doing wrong?
(Windows 10)
Server:
import socket
HOST = socket.gethostname() #Returns: "WASS104983"
#I have also tried socket.gethostbyname(socket.gethostname)), returning: "25.38.252.147"
PORT = 50007
sock = socket.socket()
sock.bind((HOST, PORT))
sock.listen(5)
print("Awaiting connection... ")
(clnt, addr) = sock.accept()
print("Client connected")
…
and Client:
import socket
HOST = "WASS104983" #Or "25.38.252.147", depending on the servers setup
PORT = 50007
sock = socket.socket()
print("Attempting connection... ")
sock.connect((HOST, PORT))
print("Connected")
…
I have gotten this to work before so I am not sure why it's not now.
I know there are a few questions of this calibre, but none seem to cover my problem.
Also, a wifi extender should not interfere with local transmissions should it?
I have always seen servers setup as such:
import socket
import threading
bind_ip = '0.0.0.0'
bind_port = 9999
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((bind_ip, bind_port))
server.listen(5)
print("[*] Listening on {}:{}".format(bind_ip, bind_port))
def handle_client(client_socket):
request = client_socket.recv(1024)
print('received: {}'.format(request))
client_socket.send(b'ACK!')
client_socket.close()
while True:
client, addr = server.accept()
print("[*] Accepted connection from: {}:{}".format(addr[0], addr[1]))
client_handler = threading.Thread(target=handle_client, args=(client,))
client_handler.start()*
Where I think an important distinction from your post may be that the server accepting connections is within an infinite loop. Have you tried this?

Categories