无法在两个套接字脚本之间建立连接
Can't get a connection between two socket scripts
我正在尝试使用 python 中的套接字模块构建一个 tkinter 消息传递应用程序,我正在测试它,但是脚本的两个副本无法相互连接(一个托管,另一个连接)。 create_messaging_screen() 方法永远不会运行。
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()
acw1668 是正确的,我应该在 self_socket.connect('', default_port)
.
中使用 'localhost'
或类似的 IP 参数
我正在尝试使用 python 中的套接字模块构建一个 tkinter 消息传递应用程序,我正在测试它,但是脚本的两个副本无法相互连接(一个托管,另一个连接)。 create_messaging_screen() 方法永远不会运行。
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()
acw1668 是正确的,我应该在 self_socket.connect('', default_port)
.
'localhost'
或类似的 IP 参数