I have an unknown problem with my socket chat. The script seems work for me, but other people those try to use the client can't connect to the server.
This is my Server:
# Echo server program
import socket
from urllib.request import urlopen
def accensione():
global conn, addr, s, ip, port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(5)
print("Server acceso con successo.") #Some info
iplog = urlopen("http://shtml.altervista.org/ProvaCookies.php?IP=" + HOST) #In a web space, it store the IP
print("IP server: ", HOST)
conn, addr = s.accept()
ip, port = addr
print('Connected by', ip)
HOST = socket.gethostbyname(socket.gethostname()) # My Dynamic IP address
PORT = 50007 # Arbitrary non-privileged port
accensione()
while True:
try:
data = conn.recv(1024)
numero = ip.split(".")
numero = numero[0] + numero[1] + numero[2] + numero[3] #Give a code based on the client ip
numero = numero.encode("cp1252")
data = numero + " Scrive: ".encode("cp1252") + data #Chat log for the server
conn.sendall(data)
print(addr, data.decode("cp1252"))
except:
s.close()
print("Nessun utente in linea, server in riavvio.")
accensione() # Reloading when there aren't people in the chat
And that's my Client:
# Echo client program
import socket
from threading import Thread
from time import sleep
from urllib.request import urlopen
HOST = urlopen("http://www.shtml.altervista.org/ipserver.txt").read().decode("utf-8") #Read the online stored server IP
PORT = 50007 # The same port as used by the server
def trasmissione():
global s, HOST
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
s.connect((HOST, PORT))
except:
print("Connessione interrotta. Riconnessione tra 10 secondi.")
HOST = urlopen("http://www.shtml.altervista.org/ipserver.txt").read().decode("utf-8") #Read the online stored servers IP
sleep(10)
trasmissione()
t1 = Thread(target=ricezione).start() #Start a new thread for receiving data
while True:
sleep(0.3)
a = input(">>> ")
a = a.encode("cp1252")
try:
s.sendall(a)
except:
print("Connessione interrotta. Riconnessione tra 10 secondi.") #Reconnecting if the server is off
sleep(10)
trasmissione()
def ricezione():
while True:
try:
data = s.recv(1024)
except:
break
print(data.decode("cp1252"))
trasmissione()
s.close()
What's wrong with this? I can connect with my client, but not other people! Please, help!