I want to send data more than once. I have the following code on server and client:
On server :
import socket
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setup(14,GPIO.OUT)
GPIO.setup(15,GPIO.OUT)
serversocket=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
host="10.168.1.50"
port=80
print(host)
print(port)
serversocket.bind((host,port))
serversocket.listen(5)
print('server started listening')
while 1:
(clientsocket,address)=serversocket.accept()
print("connection established from : ",address)
data=clientsocket.recv(1024).decode()
print(data)
if (data=='hai'):
GPIO.output(14,True)
GPIO.output(15,False)
print 'hello'
else:
GPIO.output(14,False)
GPIO.output(15,False)
clientsocket.send("data is sent".encode())
On client:
import socket
s = socket.socket()
host = "10.168.1.50"
port = 80
s.connect((host,port))
while True:
in_data=raw_input(" Enter data to be sent > ")
s.send(in_data.encode())
s.send('hai'.encode())
data = ''
data = s.recv(1024).decode()
print (data)
s.close
I send the first string, get the response, but when I send the second string, it hangs.
How can I solve this?
Here is the code that worked
On server :
import socket
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setup(14,GPIO.OUT)
GPIO.setup(15,GPIO.OUT)
serversocket=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
host="10.168.1.50"
port=80
print(host)
print(port)
serversocket.bind((host,port))
serversocket.listen(5)
print('server started listening')
(clientsocket,address)=serversocket.accept()
print("connection established from : ",address)
while 1:
data=clientsocket.recv(1024).decode()
print(data)
if (data=='hai'):
GPIO.output(14,True)
GPIO.output(15,False)
print 'hello'
else:
GPIO.output(14,False)
GPIO.output(15,False)
clientsocket.send("data is sent".encode())
On client:
import socket
s = socket.socket()
host = "10.168.1.50"
port = 80
s.connect((host,port))
try:
while True:
in_data=raw_input(" Enter data to be sent > ")
s.send(in_data.encode())
data = ''
data = s.recv(1024).decode()
print (data)
finally:
s.close()
This my client and it's working.
import socket
s = socket.socket()
host = "10.168.1.50"
port = 80
s.connect((host,port))
try:
while True:
in_data=raw_input(" Enter data to be sent > ")
s.send(in_data.encode())
s.send('hai'.encode())
data = ''
data = s.recv(1024).decode()
print (data)
finally:
s.close()
Related
I have a server using socket and multi threading in python I am trying to send data to one client, I can send to both clients using connection.sendall but that sends to both.
Is there a way to send to one client using something like IP address or socket id?
Here is my server.
import socket
from _thread import start_new_thread, get_ident
import pickle
import random
host = '127.0.0.1' #host for socket
port = 46846 #port
ThreadCount = 0
connections = 0
clients = []
name = []
turn = 1
word = random.choice(open('words.txt').read().splitlines()).lower().encode() #grab a word from my file of words
def game(connection): #the games code
print(get_ident()) #id of the socket
name.append(connection.recv(2048).decode('utf-8')) #wait for name
print(name)
while 1: # wait for 2 names
if len(name) == 2:
break
pickled_name = pickle.dumps(name) #encode names
connection.sendall(pickled_name) #send encoded names
connection.sendall(word) #send the word
connection.close() #end off the connection, I want more before this but this is the end for now
def accept_connections(ServerSocket): #start a connection
global connections
Client, address = ServerSocket.accept()
print(f'Connected to: {address[0]}:{str(address[1])}')
start_new_thread(game, (Client, ))
clients.append(Client)
connections = connections + 1
print(connections)
print(clients)
def start_server(host, port): #start the server
ServerSocket = socket.socket()
try:
ServerSocket.bind((host, port))
except socket.error as e:
print(str(e))
print(f'Server is listing on the port {port}...')
ServerSocket.listen()
while True:
accept_connections(ServerSocket)
start_server(host, port)
And here is my client
import socket
import pickle
host = '127.0.0.1'
port = 46846
ClientSocket = socket.socket() #start socketing
print('Waiting for connection')
try:
ClientSocket.connect((host, port)) #connect
except socket.error as e:
print(str(e))
player = input('Your Name: ') #grab name
ClientSocket.send(str.encode(player)) #send name and encode it
data = ClientSocket.recv(1024)
name = ""
while name == "":
name = pickle.loads(data) #grab names from server
mistakeMade=0
print(f"Welcome to the game, {name[0]}, {name[1]}")
word = ClientSocket.recv(1024).decode('utf-8')
print("I am thinking of a word that is",len(word),"letters long.")
print("-------------")
turn = ClientSocket.recv(1024)
print(turn)
I am using my server code on a raspberry pi and my client code on my laptop. I also off the firewall on my computer. After connecting to the server, I manage to run the loop for once from the client side by keying the word "data" and when I keyed in another command it just came out of the loop. If i key in Quit it says that it have an OS error98 address already in used. May I know how to keep the loop on going ? Below I is my client.py and server.py code.
Server.py code:
import socket
import numpy as np
import encodings
HOST = '192.168.1.65'
PORT = 65432 # Port to listen on (non-privileged ports are > 1023)
def random_data(): # ANY DATA YOU WANT TO SEND WRITE YOUR SENSOR CODE HERE
x1 = np.random.randint(0, 55, None) # Dummy temperature
y1 = np.random.randint(0, 45, None) # Dummy humidigy
my_sensor = "{},{}".format(x1,y1)
return my_sensor # return data seperated by comma
def my_server():
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
print("Server Started waiting for client to connect ")
s.bind((HOST, PORT))
s.listen(5)
conn, addr = s.accept()
with conn:
print('Connected by', addr)
while True:
data = conn.recv(1024).decode('utf-8')
if str(data) == "Data":
print("Ok Sending data ")
my_data = random_data()
x_encoded_data = my_data.encode('utf-8')
conn.sendall(x_encoded_data)
elif str(data) == "Quit":
print("shutting down server ")
break
else:
pass
if __name__ == '__main__':
while 1:
my_server()
Client.py Code:
import socket
import threading
import time
HOST = '192.168.1.65' # The server's hostname or IP address
PORT = 65432 # The port used by the server
def process_data_from_server(x):
x1, y1 = x.split(",")
return x1,y1
def my_client():
threading.Timer(11, my_client).start()
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((HOST, PORT))
my = input("Enter command ")
my_inp = my.encode('utf-8')
s.sendall(my_inp)
data = s.recv(1024).decode('utf-8')
x_temperature,y_humidity = process_data_from_server(data)
print("Temperature {}".format(x_temperature))
print("Humidity {}".format(y_humidity))
s.close()
time.sleep(5)
if __name__ == "__main__":
while 1:
my_client()
address already used
you need to use socket.setsockopt to set socket.SO_REUSEADDR in i think both client and server.py
def my_server():
# with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
print("Server Started waiting for client to connect ")
s.bind((HOST, PORT))
s.listen(5)
conn, addr = s.accept()
with conn:
print('Connected by', addr)
while True:
data = conn.recv(1024).decode('utf-8')
if str(data) == "Data":
...
I am making server-client communication in python using sockets and threading module. I connect client to server, send some data, receive some data, but the problem is, I can send only two messages. After those, the server is not reciving my packets. Can someone tell me what's wrong? Thanks in advance.
Server.py:
import socket
from threading import Thread
class Server:
def __init__(self):
self.host = '127.0.0.1'
self.port = 9999
self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.server.bind((self.host, self.port))
self.server.listen(5)
self.threads = []
self.listen_for_clients()
def listen_for_clients(self):
print('Listening...')
while True:
client, addr = self.server.accept()
print('Accepted Connection from: '+str(addr[0])+':'+str(addr[1]))
self.threads.append(Thread(target=self.handle_client, args=(client, addr)))
for thread in self.threads:
thread.start()
def handle_client(self, client_socket, address):
client_socket.send('Welcome to server'.encode())
size = 1024
while True:
message = client_socket.recv(size)
if message.decode() == 'q^':
print('Received request for exit from: '+str(address[0])+':'+str(address[1]))
break
else:
print('Received: '+message.decode()+' from: '+str(address[0])+':'+str(address[1]))
client_socket.send('Received request for exit. Deleted from server threads'.encode())
client_socket.close()
if __name__=="__main__":
main = Server()
Client.py
import socket
import sys, time
def main():
target_host = '127.0.0.1'
target_port = 9999
try:
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error:
print('Could not create a socket')
time.sleep(1)
sys.exit()
try:
client.connect((target_host, target_port))
except socket.error:
print('Could not connect to server')
time.sleep(1)
sys.exit()
while True:
data = input()
client.send(data.encode())
message = client.recv(4096)
print('[+] Received: '+ message.decode())
main()
You have to send exit message 'q^' to client too to close client.
Warning:
Using Unicode as encoding for string is not recommended in socket. A partial Unicode character may be received in server/client resulting in UnicodeDecodeError being raised.
Code for server using threads is:
server.py:
import socket
from threading import Thread
class Server:
def __init__(self, host, port):
self.host = host
self.port = port
self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.server.bind((self.host, self.port))
self.server.listen(5)
def listen_for_clients(self):
print('Listening...')
while True:
client, addr = self.server.accept()
print(
'Accepted Connection from: ' + str(addr[0]) + ':' + str(addr[1])
)
Thread(target=self.handle_client, args=(client, addr)).start()
def handle_client(self, client_socket, address):
size = 1024
while True:
try:
data = client_socket.recv(size)
if 'q^' in data.decode():
print('Received request for exit from: ' + str(
address[0]) + ':' + str(address[1]))
break
else:
# send getting after receiving from client
client_socket.sendall('Welcome to server'.encode())
print('Received: ' + data.decode() + ' from: ' + str(
address[0]) + ':' + str(address[1]))
except socket.error:
client_socket.close()
return False
client_socket.sendall(
'Received request for exit. Deleted from server threads'.encode()
)
# send quit message to client too
client_socket.sendall(
'q^'.encode()
)
client_socket.close()
if __name__ == "__main__":
host = '127.0.0.1'
port = 9999
main = Server(host, port)
# start listening for clients
main.listen_for_clients()
client.py:
import socket
import sys, time
def main():
target_host = '127.0.0.1'
target_port = 9999
try:
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error:
print('Could not create a socket')
time.sleep(1)
sys.exit()
try:
client.connect((target_host, target_port))
except socket.error:
print('Could not connect to server')
time.sleep(1)
sys.exit()
online = True
while online:
data = input()
client.sendall(data.encode())
while True:
message = client.recv(4096)
if 'q^' in message.decode():
client.close()
online = False
break
print('[+] Received: ' + message.decode())
break # stop receiving
# start client
main()
Server Code
import socket
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind(("192.168.169.10", 9559))
server_socket.listen(5)
import os
import time
client_socket, address = server_socket.accept()
print "Conencted to - ",address,"\n"
while(1):
fp = open('img.jpg','wb+')
start = time.time()
while True:
strng = client_socket.recv(1024)
if not strng:
break
print 'loop ends'
fp.write(strng)
fp.close()
print 'total time taken',time.time()-start,'secs'
print "Data Received successfully"
client_socket.send("Hey I am looking for you face")
exit()
Client Code
import socket,os
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect(("192.168.169.10", 9559))
fname = '/home/student/images/andrew1.jpeg'
img = open(fname,'rb')
while True:
strng = img.readline(1024)
if not strng:
break
client_socket.send(strng)
img.close()
response = client_socket.recv(1024)
print response
exit()
The Code gets stucked and when on the client side ctrl +C is pressed the server exits and the client doesnt receive data
How to achieve two way communication in this scenario ??
I have a python script that receives tcp data from client and I want to send a response to a specific client (I handle more than 500). This command comes from a mysql database and I handle the clientsocket by a dictionary, but the script is down when it receives a lot of connections.
How can I store the clientsocket in mysql database, or which is the best way to handle the clientsocket?
My code is:
import thread
from socket import *
def sendCommand():
try:
for clientsocket,id_client in conn_dict.iteritems():
if id_cliente == "TEST_from_mysql_db":
clientsocket.send("ACK SEND")
break
except:
print "NO"
def handler(clientsocket, clientaddr):
print "Accepted connection from: ", clientaddr
while 1:
data = clientsocket.recv(buf)
if not data:
break
else:
conn_dict[clientsocket] = id_client
sendCommand()
clientsocket.close()
if __name__ == "__main__":
conn_dict = dict()
host = str("XXX.XXX.XXX.XXX")
port = XXX
buf = 1024
addr = (host, port)
serversocket = socket(AF_INET, SOCK_STREAM)
serversocket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
serversocket.bind(addr)
serversocket.listen(2)
while 1:
print "Server is listening for connections\n"
clientsocket, clientaddr = serversocket.accept()
thread.start_new_thread(handler, (clientsocket, clientaddr))
serversocket.close()