繁体   English   中英

Python 套接字 IPV6(信使)

[英]Python Sockets IPV6 (Messenger)

所以我想用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()

将套接字更改为client_socket = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM