Search code examples
python-3.xtkinterpython-multithreadingpython-sockets

Can't get a connection between two socket scripts


I am trying to build a tkinter messaging app using the socket module in python, I was testing it, but two copies of the script cannot connect to each other (one hosting and the other connecting). The create_messaging_screen() method never runs.

import socket
from threading import Thread
import tkinter as tk

default_port = 43777
self_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

def client_link():
    self_socket.connect(('', default_port))
    create_messenging_screen()
    self_socket.sendall(("hi to you too").encode("utf-8"))
    while True:
        try:
            print(self_socket.recv(1024))
        except:pass

def host_link():
    self_socket.bind(('', default_port))

    self_socket.listen(1)

    global client_conn
    client_conn, client_addr = self_socket.accept()
    create_messenging_screen()

    client_conn.sendall(("hi").encode("utf-8"))
    print(client_addr)

    while True:
        try:
            print(client_conn.recv(1024))
        except:pass

def continue_setup(route):
    if route == None:
        Thread(target=host_link).start()
    else:
        Thread(target=client_link).start()


def create_messenging_screen():
   #clear the window and create the messaging GUI

window = tk.Tk()
#IM app connection screen

#host a chatroom
button(window, command=lambda: continue_setup(None))
#join a chatroom
button(window, command=lambda: continue_setup(1))

window.mainloop()

Solution

  • acw1668 was correct, I should've used 'localhost' or something of the like for the IP parameter in self_socket.connect('', default_port).