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")
1 Answer 1
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 (i.e. you can't call connect() on your old socket a second time).
answered Feb 15, 2021 at 2:28
Jeremy Friesner
74k18 gold badges147 silver badges258 bronze badges
Sign up to request clarification or add additional context in comments.
4 Comments
sasasa
So it is basically a new client?
Stack Exchange Broke The Law
@sasasa It's a new socket. Clients are something you made up in your program, not something to do with sockets, so that's a question for yourself.
sasasa
client_socket = socket(AF_INET, SOCK_STREAM) client_socket_2 = socket(AF_INET, SOCK_STREAM)
sasasa
Something like this? I might need some help:)
lang-py
client_socket.connectagain with a new address (or use a second client)?connect()on it with a different server address is the answer to "how to change the server"receive_threadand completely disconnect, or just have more than one server connection open and getting messages?