简体   繁体   中英

python socket chat server

After that I have connected to the server from input, how do I change my server in the chat?

I just updated the code with something that could work though it needs some more work, anyone?

def send(event=None):  # event is passed by binders.
    """Handles sending of messages."""
    global HOST
    global PORT
    global ADDR
    
    msg = my_msg.get()
    my_msg.set("")  # Clears input field.
    msg_list1 = msg.split()
    
    try:
        if msg_list1 [0] == "/connect":
        try: 
            HOST = msg_list1[1]
            PORT = int(msg_list1[2])
            ADDR = (HOST,PORT)
            client_socket.connect(ADDR)
            receive_thread = Thread(target=receive)
            receive_thread.start()
            
        except TypeError:
            msg_list_tk.insert(tt.END, "Error: please write '/connect ADDR PORT' to connect to server\n")
            
    if msg_list1 [0] == "/connectnew":
            HOST = msg_list1[1]
            PORT = int(msg_list1[2])
            ADDR = (HOST,PORT)
            client_socket_2.connect(ADDR)
            receive_thread = Thread(target=receive)
            receive_thread.start()
            except:
                msg_list_tk.insert(tt.END, "Error: please write '/connect ADDR PORT' to connect to server\n")
        elif msg == "/q":
            root.quit()
            client_socket.send(b"/q")
            
        elif msg == "/disconnect":
            client_socket.close()
            
        else:
            client_socket.send(bytes(msg, "utf8"))
    except:
        msg_list_tk.insert(tt.END, "Wrong input\n")

A TCP socket is only usable for a single TCP connection. If you want a second connection, you need to create a new socket and call connect() on that (ie you can't call connect() on your old socket a second time).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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