How do you make a socket that actually connects to other computers?

Asked

Viewed 2,883 times

1

I tried to make a Python 3.5.1 socket, but when I went to test it only connects with me. I tried to connect to another computer (from my friend), but it does not connect. Does anyone know how to make a socket that actually connects?

In case anyone wants to see, here’s my troublesome socket: http://pastebin.com/Z01Fp71K

#Cliente
import socket
HOST = 'Aqui eu coloco o ip'
PORT = 5000
tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
dest = (HOST, PORT)
tcp.connect(dest)
print('Para sair use CTRL+X\n')
msg = input()
while msg != '\x18':
    tcp.send(msg)
    msg = input()
tcp.close()
#Servidor
import socket
HOST = ''
PORT = 5000
tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
orig = (HOST, PORT)
tcp.bind(orig)
tcp.listen(1)
while True:
    con, cliente = tcp.accept()
    print('Concetado por', cliente)
    while True:
        msg = con.recv(1024)
        if not(msg): break
        print(cliente, msg)
    print('Finalizando conexao do cliente', cliente)
    con.close()
  • 1

    If it worked for you it’ll probably work for your friend too. What must be happening is that port 5000 must be blocked in your friend’s PC firewall. Search for how to free ports in the Windows firewall (or other operating system) you have on your PC.

  • Yes I researched it and it still doesn’t work

1 answer

2

Here it worked perfectly well, including running the server on a computer on the Internet, and using a HOST with name instead of IP on client.

The server you tried is leaking? Sometimes the computers of the same network are not accessible, either because of access point problems (a shutdown solves), or because the access point is with Isolation enabled (prevents a computer from connecting to another on the same network for security reasons, such as public Wi-Fi).

The only problem I faced when typing something for the client to send was the following:

Traceback (most recent call last):
  File "cli", line 11, in <module>
    tcp.send(msg)
TypeError: a bytes-like object is required, not 'str'

This is solved by replacing the line of tcp.send(msg) with

tcp.send(bytes(msg, 'utf-8'))

Browser other questions tagged

You are not signed in. Login or sign up in order to post.