如何在服务器套接字上发送和接收消息?

2024-10-03 09:12:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我正试图创建一个简单的“聊天室”的排序,我不知道有多少消息,我会从一个客户端,但我的服务器将接收它们,显示它们,并最终作出回应。问题是当我点击respond文本框时,我的代码崩溃了。我真的不确定我的问题在哪里,任何帮助都会奏效

from Tkinter import *
import tkMessageBox
import socket
import threading

# Global variables
SendConfirmation = "0"
ConnectionConfirmation = "0"
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
data_old = ""

# Initiates socket and connection
def ConnectBind():
    global ConnectionConfirmation
    global sock
    server_address = (IP_Entry.get(), int(Port_Entry.get()))
    sock.bind(server_address)
    tkMessageBox.showinfo("Bind Successful", "Connected to " + IP_Entry.get() + " at port " + Port_Entry.get())
    ConnectionConfirmation = "1"

# Sets the disconnect signal
def DisconnectBind():
    global ConnectionConfirmation
    ConnectionConfirmation = "2"

# Sets the Send Signal
def SendMessage():
    global SendConfirmation
    SendConfirmation="1"

# Running background listen
def BackgrounListen():
    global data_old
    data = connection.recv(1024)
    if data != None:
        if data != data_old:
            Message_Text.insert('1.0', data + '\n')

# Window set up
root = Tk()
root.title('TCP/IP software')
ConnectionFrame = Frame(root)
ConnectionFrame.pack(side=TOP, fill=X)
SendFrame = Frame(root)
SendFrame.pack(side=TOP, fill=X)
MessageFrame = Frame(root)
MessageFrame.pack(side = BOTTOM)

# Connection information frame
IP_Label = Label(ConnectionFrame, text="IP address: ")
IP_Entry = Entry(ConnectionFrame, bd=10, text="Enter IP address here")
Port_Label = Label(ConnectionFrame, text="Port number: ")
Port_Entry = Entry(ConnectionFrame, bd=10, text="Enter port number here")
IP_Label.grid(row=0, column=0)
IP_Entry.grid(row=0, column=1)
Port_Label.grid(row=1, column=0)
Port_Entry.grid(row=1, column=1)
# Connect and bind to the address and port
Connect_Button = Button(ConnectionFrame, text="Connect", command=ConnectBind)
Connect_Button.grid(row=3, column=0)
DisConnect_Button = Button(ConnectionFrame, text="Disconnect", command=DisconnectBind)
DisConnect_Button.grid(row=3, column=1)

# Send messages frame
SendMessage_Entry = Entry(SendFrame, bd=10, text="Type your message here")
SendMessage_Button = Button(SendFrame, text="Send Message", command=SendMessage)
SendMessage_Entry.pack()
SendMessage_Button.pack()

# Information/Messages display frame
Message_Text = Text(MessageFrame, height=8, width=50)
Message_Scroll = Scrollbar(MessageFrame)
Message_Text.pack(side=LEFT, fill=Y)
Message_Scroll.pack(side=RIGHT, fill=Y)
Message_Scroll.config(command=Message_Text.yview())
Message_Text.config(yscrollcommand=Message_Scroll.set)

# Start the GUI before running
root.update_idletasks()
root.update()

#Working out main
Message_Text.insert(INSERT, "Software started")
while ConnectionConfirmation != "2":
    if ConnectionConfirmation == "1":
        sock.listen(1)
        connection, client_address = sock.accept()
        Message_Text.insert('1.0', "Client connected\n")
        connection.sendall("connected to server")
        root.update_idletasks()
        root.update()
        while ConnectionConfirmation == "1":
            if connection.recv#:


            # if SendConfirmation == "1":
            #     connection.send(SendMessage_Entry.get())
            #     SendConfirmation = "0"
            background_thread = threading.Thread(target=BackgrounListen())
            background_thread.daemon = True
            background_thread.start()
            root.update_idletasks()
            root.update()
    elif ConnectionConfirmation == "2":
        sock.close()
        #Message_Text.insert('1.0', "Socket properly closed")
        #ConnectionConfirmation = "0"
        #root.update_idletasks()
        #root.update()

    root.update_idletasks()
    root.update()

Tags: textipmessagedataportupdatebuttonroot
1条回答
网友
1楼 · 发布于 2024-10-03 09:12:25

最简单的方法是把聊天室做成一个反壳。 我在这里写代码。 希望对您有所帮助。;—) [代码]:server.py

import socket
s = socket.socket(socket.AF_INET , socket.SOCK_STREAM)
ip = socket.gethostname()
port = 4444
s.bind((ip , port))
name = input("Enter Your Name : ")
try :
    while True :
    s.listen(5)
    conn , addr = s.accept()
    print("Connection From : ",addr)
    while True :
       data = conn.recv(1024)
       print()
       print(data)
       print()
       msg = input("Enter the Massage : ")
       msg = name + " : " + msg
       if msg == "exit" :
           conn.close()
           s.close()
           break
       else :
           conn.send(bytes(msg , "UTF-8"))
except IOError as error :
   print("\n [!] Connection Faild [!] \n",error)
   conn.close()
   s.close()

[代码]:client.py

import socket
ip = socket.gethostname() #ip to connect
port = 4444
s = socket.socket(socket.AF_INET , socket.SOCK_STREAM)
name = input("Enter Your Name : ")
try :
    s.connect((ip , port))
    print("[+] Connected to : " , ip)
    while True :
        print()
        cmd = input("Enter the Massage : ")
        if cmd == "exit" :
            s.close()
            break
            exit()
        else :
            cmd = name + " : " + cmd
            s.send(bytes(cmd , "UTF-8"))
            data = s.recv(1024000)
            data = strings.byte2str(data)
            print()
            print(data)
except IOError as error :
    print("\nDisconnected From : ",ip,"\n",error)
    s.close()

玩得开心:-)

相关问题 更多 >