I have two scripts, Server.py and Client.py. I have two objectives in mind:
- To be able to send data again and again to server from client.
- To be able to send data from Server to client.
here 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='REceieve'
clientsocket.send(r.encode())
and here is my client :
#! /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))
def ts(str):
s.send('e'.encode())
data = ''
data = s.recv(1024).decode()
print (data)
while 2:
r = input('enter')
ts(s)
s.close ()
The function works for the first time ('e' goes to the server and I get return message back), but how do I make it happen over and over again (something like a chat application) ? The problem starts after the first time. The messages don't go after the first time. what am I doing wrong? I am new with python, so please be a little elaborate, and if you can, please give the source code of the whole thing.
This is a very VERY simple design for how you could solve it. First of all, you need to either accept the client (server side) before going into your
while 1
loop because in every loop you accept a new client, or you do as i describe, you toss the client into a separate thread which you handle on his own from now on.This piece of code is incorrect.
The call on
accept()
on theserversocket
blocks until there's a client connection. When you first connect to the server from the client, it accepts the connection and receives data. However, when it enters the loop again, it is waiting for another connection and thus blocks as there are no other clients that are trying to connect.That's the reason the
recv
works correct only the first time. What you should do is find out how you can handle the communication with a client that has been accepted - maybe by creating a new Thread to handle communication with that client and continue accepting new clients in the loop, handling them in the same way.Tip: If you want to work on creating your own chat application, you should look at a networking engine like Twisted. It will help you understand the whole concept better too.
client.py
server.py
This should be the code for a small prototype for the chatting app you wanted. Run both of them in separate terminals but then just check for the ports.