Reputation: 6034
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)?
Upvotes: 0
Views: 7787
Reputation: 448
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
Upvotes: 1