0

My object is to be able to repeatedly send some string from client to server, and also from server to client. These scripts help me send a message ONCE (one message from client to server, then one from server to client). I want to put send (in both) in some sort of loop.

this is my Server.py

import socket

serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = "192.168.1.3"
port = 8000
print (host)
print (port)
serversocket.bind((host, port))

serversocket.listen(5)
print ('server started and listening')
while 1:
    (clientsocket, address) = serversocket.accept()
    print ("connection found!")
    data = clientsocket.recv(1024).decode()
    print (data)
    r=input('ENTER HERE')
    clientsocket.send(r.encode())

and here is my Client.py

#! /usr/bin/python3

import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host ="192.168.1.3"
port =8000

s.connect((host,port))


r=input('Enter message   ') 
s.send(r.encode())
data = ''
data = s.recv(1024).decode()
print (data)




s.close ()

I want to be able to send strings from both server as well as client. But right now, the server listens for client for a message. After client sends message, only then is the server able to return a message.

Aside of this, I am able to send only 1 message each fro any side. How to enable independent message transmission (and infinite number of messages)?

0

1 Answer 1

1

You will need threads.

In server, Create two separate threads after clients get connected. One thread will continuously listen for incoming messages and another will handle the sending of message. Same thing will apply for client.

//server
//client is client_socket
def thread_read(client):
  listen_for_incoming_messages_from_client

def thread_write(client):
  message_sending_code_here


and for client side, parameter will be server (server_socket)

This way, you can handle independent messaging between clients and server

Sign up to request clarification or add additional context in comments.

3 Comments

I am new to python. could you please give the updated python files ?
sorry mate, I haven't coded them.. Just google "threads python" and refer them..I am sure, you will get along with it, cause understanding them is quite easy and fun\
I have developed Chat application in C++ and soure is too heavy to post, so trick remains same for every programming language

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.