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.
Related
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?
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 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
So i want to build simple Server-Client.
This server gets connections from clients (simple string), do my stuff, return answer, close the client connection and wait for another connections.
Client
import socket
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
ip = '127.0.0.1'
port = 4500
address = (ip, port)
message = 'mymessage'
client = socket.socket()
client.connect(address)
client.sendall(message.encode('utf-8'))
Server
import socket
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
name = socket.gethostname()
ip = '127.0.0.1'
port = 4500
address = (ip, port)
server.bind(address)
server.listen(1)
print('Start listening on', ip, ':', port)
client, addr = server.accept()
print('Received connection from', addr[0], ':', addr[1])
while True:
data = client.recv(1024).decode('utf-8')
print('Received', data, 'from the client')
# DO something.....
client.send('Goodbye'.encode('utf-8'))
client.close()
break
So currently after the client get back the response from the server the server is close and i want my server to continue listening for another connections.
Simple, you need to add another loop, so that the server can always listen:
Server
import socket
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
name = socket.gethostname()
ip = '127.0.0.1'
port = 4500
address = (ip, port)
server.bind(address)
server.listen(1)
while True:
client, addr = server.accept()
print('Start listening on', ip, ':', port)
print('Received connection from', addr[0], ':', addr[1])
while True:
data = client.recv(1024).decode('utf-8')
print('Received', data, 'from the client')
# DO something.....
client.send('Goodbye'.encode('utf-8'))
client.close()
break
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?