C
C
CeBePHblY2015-10-04 11:00:57
Python
CeBePHblY, 2015-10-04 11:00:57

Python client-server on sockets. Why doesn't the chat mode work correctly?

there is a server in python:

#!/usr/bin/env python3
import socket

host = "192.168.43.38"
port = 8080

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((host, port))
s.listen(5)
sock, addr = s.accept()
print("client connected with address " + addr[0])
sock.send(b"hello!")
while True:
  buf = sock.recv(1024)
  buf = buf.rstrip()
  if buf.decode('utf8') == "exit":
    sock.send(b"bye")
    break
  elif buf:
    sock.send(buf)
    print(buf.decode('utf8'))
sock.close()

and the client on it:
#!/usr/bin/env python3
import socket
import time

host = "192.168.43.38"
port = 8080

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))
while True:
    buf = input()
    s.send(buf.encode('utf8'))
    result = s.recv(1024)
    print('Ответ сервера: ', result.decode('utf8'))
    if buf == "exit":
        break
s.close()

time.sleep(10)

everything would be fine, but the link does not work correctly in chat mode, namely: after the client connects to the server, "client connected with address..........." is written in the server window, but the next line is "hello!" not sent to the client. further, if you write "stroka2" to the server from the client, then "stroka2" from the client will be displayed on the server, and the same string "hello!" How to fix it?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Andrey K, 2015-10-04
@CeBePHblY

#!/usr/bin/env python3
import socket
import time

host = "192.168.43.38"
port = 8080

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))
print(s.recv(1024).decode('utf8'))

while True:
    buf = input()
    s.send(buf.encode('utf8'))
    result = s.recv(1024)
    print('Ответ сервера: ', result.decode('utf8'))
    if buf == "exit":
        break
s.close()

time.sleep(10)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question