Python 套接字 IPV6(信使)
所以我想用 python 做一个信使应用程序,我创建了一个客户端脚本和一个服务器脚本,服务器可以处理多个连接并且它现在工作得很好。我现在的问题是我的 ISP 没有给我公共 ipv4。所以我需要使用 ipv6 作为服务器,有什么方法可以做到这一点吗? 那是我的服务器脚本
#!/usr/bin/env python3
"""Server for multithreaded (asynchronous) chat application."""
from socket import AF_INET, socket, SOCK_STREAM
from threading import Thread
def accept_incoming_connections():
"""Sets up handling for incoming clients."""
while True:
client, client_address = SERVER.accept()
print("%s:%s has connected." % client_address)
client.send(bytes("Enter please a Username to join this Chatroom", "utf8"))
addresses[client] = client_address
Thread(target=handle_client, args=(client,)).start()
def handle_client(client): # Takes client socket as argument.
"""Handles a single client connection."""
name = client.recv(BUFSIZ).decode("utf8")
welcome = 'Welcome %s! if you wanna quit, type {quit} to exit.' % name
client.send(bytes(welcome, "utf8"))
msg = "%s has joined the chat!" % name
broadcast(bytes(msg, "utf8"))
clients[client] = name
while True:
msg = client.recv(BUFSIZ)
if msg != bytes("{quit}", "utf8"):
broadcast(msg, name+": ")
else:
client.send(bytes("{quit}", "utf8"))
client.close()
del clients[client]
broadcast(bytes("%s has left the chat." % name, "utf8"))
break
def broadcast(msg, prefix=""): # prefix is for name identification.
"""Broadcasts a message to all the clients."""
for sock in clients:
sock.send(bytes(prefix, "utf8")+msg)
print(bytes(prefix,"utf8")+msg)
clients = {}
addresses = {}
HOST = ''
PORT = input("Port you Wanna run this Server: ")
PORT = int(PORT)
BUFSIZ = 2048
ADDR = (HOST, PORT)
SERVER = socket(AF_INET, SOCK_STREAM)
SERVER.bind(ADDR)
if __name__ == "__main__":
SERVER.listen(5)
print("Waiting for connection...")
ACCEPT_THREAD = Thread(target=accept_incoming_connections)
ACCEPT_THREAD.start()
ACCEPT_THREAD.join()
SERVER.close()
那是我的客户端脚本
import tkinter as tk
import threading
import socket
from playsound import playsound
from socket import AF_INET, socket, SOCK_STREAM
from threading import Thread
from tkinter import *
from tkinter import Tk,Label
HOST = input("IP/Host: ")
PORT = input("Port of the Server: ")
PORT = int(PORT)
root = tk.Tk()
root.title('Bens Messager')
root.geometry('450x600')
root.config(bg = "black")
ShouldIPlay = 1
def PlayTheSound():
global ShouldIPlay
if ShouldIPlay == 1:
playsound("KlingelTon.mp3")
else:
ShouldIPlay = 1
def func():
t = threading.Thread(target = recv)
t.start()
def recv():
while True:
try:
msg = client_socket.recv(BUFSIZ).decode("utf8")
lstbx.insert(0, msg)
PlayTheSound()
except OSError: # Possibly client has left the chat.
break
def sendmsg(event=None):
global ShouldIPlay
msg = message.get()
message.set("") # Clears input field.
client_socket.send(bytes(msg, "utf8"))
ShouldIPlay = 0
if msg == "{quit}":
client_socket.close()
root.quit()
def threadsendmsg(event):
th = threading.Thread(target = sendmsg)
th.start()
def threadsendmsg2():
th = threading.Thread(target = sendmsg)
th.start()
def on_closing(event=None):
"""This function is to be called when the window is closed."""
message.set("{quit}")
sendmsg()
root.bind("<Return>", threadsendmsg)
message = StringVar()
messagebox = Entry(root, textvariable = message, font = ('carlibre', 10, 'normal'), border = 2, width = 45)
messagebox.config(bg = "grey")
messagebox.place(x = 10, y = 544)
sendmessageimg = PhotoImage(file = 'SendButton.png')
sendmessagebutton = Button(root, image = sendmessageimg ,command = threadsendmsg2, borderwidth = 0)
sendmessagebutton.place(x = 340, y = 530)
sendmessagebutton.config(bg = "black")
lstbx = Listbox(root, height = 27, width = 70)
lstbx.place(x = 15, y = 80)
lstbx.config(bg = "grey")
#----Now comes the sockets part----
BUFSIZ = 2048
ADDR = (HOST, PORT)
client_socket = socket(AF_INET, SOCK_STREAM)
client_socket.connect(ADDR)
receive_thread = Thread(target=recv)
receive_thread.start()
root.mainloop()
So i wanna do a messenger App with python,i created a Client script and a server script, the server can handle multiple connections and its working all fine right now. My problem right now is that my ISP dont give me a public ipv4. so i need to use ipv6 for the server, any way to do that?
Thats my Server script
#!/usr/bin/env python3
"""Server for multithreaded (asynchronous) chat application."""
from socket import AF_INET, socket, SOCK_STREAM
from threading import Thread
def accept_incoming_connections():
"""Sets up handling for incoming clients."""
while True:
client, client_address = SERVER.accept()
print("%s:%s has connected." % client_address)
client.send(bytes("Enter please a Username to join this Chatroom", "utf8"))
addresses[client] = client_address
Thread(target=handle_client, args=(client,)).start()
def handle_client(client): # Takes client socket as argument.
"""Handles a single client connection."""
name = client.recv(BUFSIZ).decode("utf8")
welcome = 'Welcome %s! if you wanna quit, type {quit} to exit.' % name
client.send(bytes(welcome, "utf8"))
msg = "%s has joined the chat!" % name
broadcast(bytes(msg, "utf8"))
clients[client] = name
while True:
msg = client.recv(BUFSIZ)
if msg != bytes("{quit}", "utf8"):
broadcast(msg, name+": ")
else:
client.send(bytes("{quit}", "utf8"))
client.close()
del clients[client]
broadcast(bytes("%s has left the chat." % name, "utf8"))
break
def broadcast(msg, prefix=""): # prefix is for name identification.
"""Broadcasts a message to all the clients."""
for sock in clients:
sock.send(bytes(prefix, "utf8")+msg)
print(bytes(prefix,"utf8")+msg)
clients = {}
addresses = {}
HOST = ''
PORT = input("Port you Wanna run this Server: ")
PORT = int(PORT)
BUFSIZ = 2048
ADDR = (HOST, PORT)
SERVER = socket(AF_INET, SOCK_STREAM)
SERVER.bind(ADDR)
if __name__ == "__main__":
SERVER.listen(5)
print("Waiting for connection...")
ACCEPT_THREAD = Thread(target=accept_incoming_connections)
ACCEPT_THREAD.start()
ACCEPT_THREAD.join()
SERVER.close()
And that is my Client script
import tkinter as tk
import threading
import socket
from playsound import playsound
from socket import AF_INET, socket, SOCK_STREAM
from threading import Thread
from tkinter import *
from tkinter import Tk,Label
HOST = input("IP/Host: ")
PORT = input("Port of the Server: ")
PORT = int(PORT)
root = tk.Tk()
root.title('Bens Messager')
root.geometry('450x600')
root.config(bg = "black")
ShouldIPlay = 1
def PlayTheSound():
global ShouldIPlay
if ShouldIPlay == 1:
playsound("KlingelTon.mp3")
else:
ShouldIPlay = 1
def func():
t = threading.Thread(target = recv)
t.start()
def recv():
while True:
try:
msg = client_socket.recv(BUFSIZ).decode("utf8")
lstbx.insert(0, msg)
PlayTheSound()
except OSError: # Possibly client has left the chat.
break
def sendmsg(event=None):
global ShouldIPlay
msg = message.get()
message.set("") # Clears input field.
client_socket.send(bytes(msg, "utf8"))
ShouldIPlay = 0
if msg == "{quit}":
client_socket.close()
root.quit()
def threadsendmsg(event):
th = threading.Thread(target = sendmsg)
th.start()
def threadsendmsg2():
th = threading.Thread(target = sendmsg)
th.start()
def on_closing(event=None):
"""This function is to be called when the window is closed."""
message.set("{quit}")
sendmsg()
root.bind("<Return>", threadsendmsg)
message = StringVar()
messagebox = Entry(root, textvariable = message, font = ('carlibre', 10, 'normal'), border = 2, width = 45)
messagebox.config(bg = "grey")
messagebox.place(x = 10, y = 544)
sendmessageimg = PhotoImage(file = 'SendButton.png')
sendmessagebutton = Button(root, image = sendmessageimg ,command = threadsendmsg2, borderwidth = 0)
sendmessagebutton.place(x = 340, y = 530)
sendmessagebutton.config(bg = "black")
lstbx = Listbox(root, height = 27, width = 70)
lstbx.place(x = 15, y = 80)
lstbx.config(bg = "grey")
#----Now comes the sockets part----
BUFSIZ = 2048
ADDR = (HOST, PORT)
client_socket = socket(AF_INET, SOCK_STREAM)
client_socket.connect(ADDR)
receive_thread = Thread(target=recv)
receive_thread.start()
root.mainloop()
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
将套接字更改为
client_socket = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
。Change the socket to
client_socket = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
.