我想让应用程序像信使一样,所以我按照本教程进行操作。我只是想尝试一下,如果它有效,我会继续改进它。我做了我应该做的一切并且它有效..但是,只有在本地主机..有没有办法让它像..在我的IP上创建服务器,然后例如,我的朋友将加入它,我们可以一起输入?
This is my server code:
import threading
import socket
host = '127.0.0.1'
port = 55555
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((host, port))
server.listen()
clients = []
nicknames = []
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()
nickname = nicknames[index]
broadcast(f'{nickname} left conversation'.encode('ascii'))
nicknames.remove(nickname)
break
def receive():
while True:
client, adress = server.accept()
print(f"you connected to {str(adress)}")
client.send('NICK'.encode('ascii'))
nickname = client.recv(1024).decode('ascii')
nicknames.append(nickname)
clients.append(client)
print(f'yur nickname is {nickname}')
broadcast(f'{nickname} joined!'.encode('ascii'))
client.send('connected!'.encode('ascii'))
thread = threading.Thread(target=handle, args=(client,))
thread.start()
receive()
And this is my client code :
import threading
import socket
nickname = input("How did they call you in kindergarden ?: ")
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(('127.0.0.1', 55555))
def receive():
while True:
try:
message = client.recv(1024).decode('ascii')
if message == 'NICK':
client.send(nickname.encode('ascii'))
else:
print(message)
except:
print("Theres an error.. lets find it together !")
client.close()
break
def write():
while True:
message = f'{nickname}: {input("")} '
client.send(message.encode('ascii'))
receive_thread = threading.Thread(target=receive)
receive_thread.start()
write_thread = threading.Thread(target=write)
write_thread.start()
我想在 tkinter 中制作它,所以你的 ip 会有标签。您将有 2 个应用程序。第一个服务器和第二个客户端。如果您启动服务器然后启动客户端,您将在该 IP 上加入客户端,然后您的朋友也可以加入...有没有这样的方法?