Answer the question
In order to leave comments, you need to log in
How to keep a socket connection in Python?
I decided to make a chat in Python 2.7. Client code:
import socket
message = raw_input('> ')
sock = socket.socket()
sock.connect(('127.0.0.1', 9090))
sock.send(message)
data = sock.recv(1024)
sock.close()
print data
import socket
sock = socket.socket()
sock.bind(('', 9090))
sock.listen(1)
conn, addr = sock.accept()
print 'Connected: ', addr
while True:
data = conn.recv(1024)
if not data:
break
print addr, 'sent a message: ', data
conn.send(data.upper())
conn.close()
Answer the question
In order to leave comments, you need to log in
The server should have 2 cycles.
There should also be an infinite loop before accept() to accept a new client after the old one has been dealt with.
conn.close() is not the end of the server, but the client ("dealt with the old one").
And in general, it is better to run each of them in its own thread so that they do not wait for each other. Although, this is a moot point. Some will say it's bullshit. But if there are only 30 clients, then it certainly makes no sense to feel sorry for the flows.
But while this is helloworld, this problem is not relevant at all.
But you still have so much ahead of you.
The full-fledged code of a reliable (not crashing on the first break) TCP-client-server is 5 times longer.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question