Reputation: 39
When i run main and client's py files not showing error but doesn't show the input to send the message. how to fix?
main.py result -- > Waiting... and connected 192.168.1.26 58767
clients.py result -- > nothing
this is main.py
import threading
import socket
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
host="192.168.1.26"
port=1111
threadcount=0
server.bind((host,port))
print("Waiting...")
server.listen(3)
def clients(connection):
connection.send(str.encode("welcome\n"))
while True:
data=connection.recv(2048)
reply="server says" + data.decode("utf-8")
if not data:
break
connection.sendall(str.encode(reply))
connection.close()
while True:
client,adress=server.accept()
print("connected"+ str(adress[0]) + " " + str(adress[1]))
threading.Thread(target=clients,args=(client,))
threadcount+=1
server.close()
this is clients.py
import socket
client_socket=socket.socket()
host="192.168.1.26"
port=1111
client_socket.connect((host,port))
response=client_socket.recv(1024)
print("hello")
while True:
input=input("say")
client_socket.send(str.encode(input))
Response=client_socket.recv(1024)
print(Response.decode("utf-8"))
client_socket.close()
Upvotes: 1
Views: 45
Reputation: 3229
It looks like your thread is never actually starting. One solution is to define a class that implements your thread logic in a run
routine. The class should inherit threading.Thread
. Then you can simply initialize the class as an object and call its start
routine. Try the following variant of your original server code.
import threading
import socket
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
host="192.168.1.26"
port=1111
threadcount=0
server.bind((host,port))
print("Waiting...")
server.listen(3)
class ServerThread(threading.Thread):
def __init__(self, threadsocket):
threading.Thread.__init__(self)
self.threadsocket = threadsocket
def run(self):
self.threadsocket.send(str.encode("welcome\n"))
while True:
data=self.threadsocket.recv(2048)
reply="server says" + data.decode("utf-8")
print(reply)
if not data:
break
self.threadsocket.sendall(str.encode(reply))
self.threadsocket.close()
while True:
client,adress=server.accept()
print("connected"+ str(adress[0]) + " " + str(adress[1]))
thread = ServerThread(client)
thread.start()
threadcount+=1
server.close()
As far as the client, as I mentioned in a comment you should not use input
as a variable name to store the result of the input
function. Change it to something like data
instead.
Upvotes: 2