C
C
c6h12o42018-03-22 19:04:43
Python
c6h12o4, 2018-03-22 19:04:43

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


and server:
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()

One message goes great. Then the server and client are closed. I tried to comment out conn.close, and as soon as I did not pervert, but the result is the same.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
VrencchBug, 2018-03-22
@VrencchBug

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.

Q
qyui, 2018-08-21
@qyui

Your code works fine for me. You just need to run it not from under Idle, but from the command line.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question