the code of socket-server and the code of socket-client can run perfectly on my localhost, but when I run the code of socket-server on Ubuntu server, the code of socket-client on my localhost can't connect to Ubuntu server.And the code of socket-client on Ubuntu Server can't connect to my localhost Server.
socket-server.py
import socket
import threading
def bbs(conn):
user_list.append(conn)
try:
while 1:
msg = conn.recv(1024)
if msg:
for user in user_list:
user.send(msg)
except ConnectionResetError:
user_list.remove(conn)
conn.close()
user_list = []
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(('0.0.0.0', 18000))
server.listen()
while 1:
conn, addr = server.accept()
t = threading.Thread(target=bbs, args=(conn,))
t.start()
socket-client.py
import socket
import threading
import time
def send_msg():
while 1:
msg = input()
client.send((name + ':' + msg).encode('utf-8'))
def recv_msg():
while 1:
msg = client.recv(1024)
if msg:
try:
print(msg.decode('utf-8'))
time.sleep(1)
except UnicodeDecodeError:
pass
name = input('请输入你的昵称:')
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(('10.26.8.132', 18000))
sendmsg_thread = threading.Thread(target=send_msg)
recvmsg_thread = threading.Thread(target=recv_msg)
sendmsg_thread.start()
recvmsg_thread.start()
Server is always wait for connection, Client report an error:
TimeoutError: [WinError 10060] The connection attempt failed because the connecting party did not respond correctly after a period of time or because the connecting host did not respond.
Wang if this works without issue on your localhost, but not over a network connection, it might be a firewall issue on both client & server. You can use 'nc' (netcat) for testing the connection from client to the server.
Related
I'm able to start up the server script and get it running no problem, but every time i try to connect with my client script it keeps saying connection refused. I tried running the script on both Linux and windows. For the client and server I tried changing the HOST variable by using just "localhost" as well as gethostbyname.
import socket
from time import ctime
from random import *
PORT = 2222
s= socket.socket(socket.AF_INET,socket.SOCK_STREAM)
HOST = socket.gethostbyname("localhost")
ADDRESS=(HOST,PORT)
def random_integer_division():
random.randint(1,500)
x = random.randint(1,500)
y = random.randint(1,500)
print(x)
print(y)
if x>y:
return(x//y)
else:
return(y//x)
s.bind(ADDRESS)
s.listen(7)
while True:
print("Waiting for connection. . .")
c, addr = s.accept()
#prints clients address
print(f'... conneceted form: {addr}')
c.send(bytes(f'Information returned form server: \n{str(random_integer_division())}'))
print("CLient disconnected")
c.close()
print("\nClient connection closed")
import socket
from codecs import decode
#HOST = "localhost"
PORT = 2222
HOST = socket.gethostbyname("localhost")
ADDRESS=(HOST,PORT)
#calling socket to create a bew sicket object
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.connect(ADDRESS)
dayAndTime = decode(s.recv(BUFSIZE), "ascii")
print(dayAndTIme)
s.close()
print("\nConnection to server closed")
That means your server wasn't active when trying to connect with the client.
Your code has a few typos in it which are problematic but otherwise it just needs to be split into two separate files.
I split them and cleaned up a bit in the blocks below, which should work. I made some inline notes where I made changes. Be sure to run the server first, and then run the client in a separate terminal.
client.py
import socket
PORT = 2222
HOST = socket.gethostbyname("localhost")
ADDRESS=(HOST,PORT)
#calling socket to create a new socket object
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(ADDRESS)
dayAndTime = s.recv(BUFSIZE).decode("utf-8") # changed decode method
print(dayAndTime) # you had a type here
s.close()
print("\nConnection to server closed")
server.py
import socket
import random # you had the wrong import here
PORT = 2222
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
HOST = socket.gethostbyname("localhost")
ADDRESS=(HOST,PORT)
def random_integer_division(): # unneeded code here
x = random.randint(1,500)
y = random.randint(1,500)
print(x)
print(y)
if x>y:
return(x//y)
else:
return(y//x)
s.bind(ADDRESS)
while True:
s.listen(7) # moved this inside the while loop.
print("Waiting for connection. . .")
c, addr = s.accept()
#prints clients address
print(f'... conneceted form: {addr}')
# changed the method used to encode string
c.send(f'Information returned form server: \n{str(random_integer_division())}'.encode("utf-8")))
print("Client Disconnected")
c.close()
print("\nClient connection closed")
I wrote a chat server with python and socket. Clients can connect to it via the local network but i need the clients to be able to connect to the server from another networks. I tried using 0.0.0.0 for the host IP in the server and I got this error message when trying to connect to it via another network
TimeoutError: [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond
This is my code for the server
import threading
import socket
host = "0.0.0.0"
port = 55555
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((host, port))
server.listen()
clients = []
usernames = []
print("Server is online and running......")
def broadcast(message):
for client in clients:
client.send(message)
def handle(client):
while True:
try:
message = client.recv(1024)
broadcast(message)
except:
index = clients.index(client)
clients.remove(client)
client.close()
user = usernames[index]
broadcast(f"{user} left the chat!".encode("ascii"))
usernames.remove(user)
break
def receive():
while True:
client, address = server.accept()
print(f"Connected With {str(address)}")
client.send("NICK".encode("ascii"))
username = client.recv(1024).decode("ascii")
usernames.append(username)
clients.append(client)
print(f"Username - {username}")
broadcast(f"{username} just Joined the chat!".encode("ascii"))
client.send("connected to the server!".encode("ascii"))
thread = threading.Thread(target=handle, args=(client,))
thread.start()
receive()
And this is the code for the client
import socket
import threading
username = input("Your username : ")
host = "172.28.0.2"
port = 12344
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect((host, port))
def receive():
while True:
try:
message = client.recv(1024).decode("ascii")
if message == "NICK":
client.send(username.encode("ascii"))
else:
print(message)
except:
print("An error occurred!")
client.close()
break
def write():
while True:
message = f"{username}: {input('')}"
client.send(message.encode("ascii"))
receive_thread = threading.Thread(target=receive)
receive_thread.start()
write_thread = threading.Thread(target=write)
write_thread.start()
Basically I need the clients to be able connect to the server that is running on my computer from their computers without a local network.
The easist way is that your server can apply for a public IP in WLAN, not a private internal IP behind some router or NAT devices. It can also works if here is a relay server in public.
If you can't, then you need to do NAT traverse to pounch a hole, so that external clients can get in touch with the server which is behind router. For this, you can google and use TURN/STUN/ICE.
I know this topic is not new. There is various information out there although, the robust solution is not presented (at least I did not found). I have a P2P daemon written in python3 and the last element on the pie is to connect two clients behind the NAT via TCP. My references for this topic:
https://bford.info/pub/net/p2pnat/
How to make 2 clients connect each other directly, after having both connected a meeting-point server?
Problems with TCP hole punching
What I have done so far:
SERVER:
#!/usr/bin/env python3
import threading
import socket
MY_AS_SERVER_PORT = 9001
TIMEOUT = 120.0
BUFFER_SIZE = 4096
def get_my_local_ip():
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
# doesn't even have to be reachable
s.connect(('10.255.255.255', 1))
IP = s.getsockname()[0]
except Exception:
IP = '127.0.0.1'
finally:
s.close()
return bytes(IP, encoding='utf-8')
def wait_for_msg(new_connection, client_address):
while True:
try:
packet = new_connection.recv(BUFFER_SIZE)
if packet:
msg_from_client = packet.decode('utf-8')
client_connected_from_ip = client_address[0]
client_connected_from_port = client_address[1]
print("We have a client. Client advertised his local IP as:", msg_from_client)
print(f"Although, our connection is from: [{client_connected_from_ip}]:{client_connected_from_port}")
msg_back = bytes("SERVER registered your data. Your local IP is: " + str(msg_from_client) + " You are connecting to the server FROM: " + str(client_connected_from_ip) + ":" + str(client_connected_from_port), encoding='utf-8')
new_connection.sendall(msg_back)
break
except ConnectionResetError:
break
except OSError:
break
def server():
sock = socket.socket()
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
sock.bind((get_my_local_ip().decode('utf-8'), MY_AS_SERVER_PORT))
sock.listen(8)
sock.settimeout(TIMEOUT)
while True:
try:
new_connection, client_address = sock.accept()
if new_connection:
threading.Thread(target=wait_for_msg, args=(new_connection,client_address,)).start()
# print("connected!")
# print("")
# print(new_connection)
# print("")
# print(client_address)
msg = bytes("Greetings! This message came from SERVER as message back!", encoding='utf-8')
new_connection.sendall(msg)
except socket.timeout:
pass
if __name__ == '__main__':
server()
CLIENT:
#!/usr/bin/python3
import sys
import socket
import time
import threading
SERVER_IP = '1.2.3.4'
SERVER_PORT = 9001
# We don't want to establish a connection with a static port. Let the OS pick a random empty one.
#MY_AS_CLIENT_PORT = 8510
TIMEOUT = 3
BUFFER_SIZE = 4096
def get_my_local_ip():
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
# doesn't even have to be reachable
s.connect(('10.255.255.255', 1))
IP = s.getsockname()[0]
except Exception:
IP = '127.0.0.1'
finally:
s.close()
return bytes(IP, encoding='utf-8')
def constantly_try_to_connect(sock):
while True:
try:
sock.connect((SERVER_IP, SERVER_PORT))
except ConnectionRefusedError:
print(f"Can't connect to the SERVER IP [{SERVER_IP}]:{SERVER_PORT} - does the server alive? Sleeping for a while...")
time.sleep(1)
except OSError:
#print("Already connected to the server. Kill current session to reconnect...")
pass
def client():
sock = socket.socket()
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
#sock.bind((get_my_local_ip().decode('utf-8'), MY_AS_CLIENT_PORT))
sock.settimeout(TIMEOUT)
threading.Thread(target=constantly_try_to_connect, args=(sock,)).start()
while True:
try:
packet = sock.recv(BUFFER_SIZE)
if packet:
print(packet)
sock.sendall(get_my_local_ip())
except OSError:
pass
if __name__ == '__main__':
client()
Now the current code results:
./tcphole_server.py
We have a client. Client advertised his local IP as: 10.10.10.50
Although, our connection is from: [89.22.11.50]:32928
We have a client. Client advertised his local IP as: 192.168.1.20
Although, our connection is from: [78.88.77.66]:51928
./tcphole_client1.py
b'Greetings! This message came from SERVER as message back!'
b'SERVER registered your data. Your local IP is: 192.168.1.20 You are connecting to the server FROM: 89.22.11.50:32928'
./tcphole_client2.py
b'Greetings! This message came from SERVER as message back!'
b'SERVER registered your data. Your local IP is: 10.10.10.50 You are connecting to the server FROM: 78.88.77.66:51928'
As you can see the server has all information to connect two clients. We can send details about the other peer individually through the current server-client connection.
Now two questions remain in my head:
Assuming the SERVER sends information about CLIENT 1 and CLIENT 2 for each of the peers. And now the CLIENTS starts connecting like [89.22.11.50]:32928 <> [78.88.77.66]:51928 Does the SERVER should close the current connections with the CLIENTS?
How the CLIENT Router behaves? I assume it expecting the same EXTERNAL SERVER SRC IP [1.2.3.4], instead gets one of the CLIENTS EXT IP for instance [89.22.11.50] or [78.88.77.66]?
This is messier than I thought. Any help to move forward appreciated. Hope this would help other Devs/DevOps too.
Finally found the expected behavior! Don't want to give too much code here but I hope after this you will understand the basics of how to implement it. Best to have a separate file in each of the client's folder - nearby ./tcphole_client1.py and ./tcphole_client2.py. We need to connect fast after we initiated sessions with the SERVER. Now for instance:
./tcphole_client_connector1.py 32928 51928
./tcphole_client_connector2.py 51928 32928
Remember? We need to connect to the same ports as we initiated with SERVER:
[89.22.11.50]:32928 <> [78.88.77.66]:51928
The first port is needed to bind the socket (OUR). With the second port, we are trying to connect to the CLIENT. The other CLIENT doing the same procedure except it binds to his port and connects to yours bound port. If the ROUTER still has an active connection - SUCCESS.
I have server and client side scripts for running a simple text transfer program, The server side works fine its just that when i connect with the client it show the error in the title.
Here is the client side code:
import socket
import select
import sys
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
IP = "127.0.0.1"
PORT = 33000
server.connect((IP, PORT))
while True:
sockets_list = [sys.stdin, server]
read_sockets, write_socket, error_socket = select.select(sockets_list,[],[])
for socks in read_sockets:
if socks == server:
message = socks.recv(2048)
print(message)
else:
message = sys.stdin.readline()
server.send(message)
sys.stdout.write("ME: ")
sys.stdout.write(bytes(message, "ascii"))
sys.stdout.flush()
server.close()
I am trying to create a simple web server with python using the following code.
However, When I run this code, I face this error:
ConnectionRefusedError: [WinError 10061] No connection could be made
because the target machine actively refused it
It worths mentioning that I have already tried some solutions suggesting manipulation of proxy settings in internet options. I have run the code both in the unticked and the confirmed situation of the proxy server and yet cannot resolve the issue.
Could you please guide me through this ?
import sys
import socketserver
import socket
hostname = socket.gethostname()
print("This is the host name: " + hostname)
port_number = 60000
soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
soc.connect((hostname,port_number))
Standard EXAMPLE of socket connection
SERVER & CLIENT
run this in your IDLE
import time
import socket
import threading
HOST = 'localhost' # Standard loopback interface address (localhost)
PORT = 60000 # Port to listen on (non-privileged ports are > 1023)
def server(HOST,PORT):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)
while True:
conn, addr = s.accept()
data = conn.recv(1024)
if data:
print(data)
data = None
time.sleep(1)
print('Listening...')
def client(HOST,PORT,message):
print("This is the server's hostname: " + HOST)
soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
soc.connect((HOST,PORT))
soc.send(message)
soc.close()
th=threading.Thread(target = server,args = (HOST,PORT))
th.daemon = True
th.start()
After running this, in your IDLE execute this command and see response
>>> client(HOST,PORT,'Hello server, client sending greetings')
This is the server's hostname: localhost
Hello server, client sending greetings
>>>
If you try to do server with port 60000 but send message on different port, you will receive the same error as in your OP. That shows, that on that port is no server listening to connections