I'm trying to use a socket with client server communication using python and I want through my client send a latitude, longitude, an hour and a date to get a pressure and a temperature that is in my grib file but my client script gives me this error
Client "JSON_OBJECT = response.loads (response.read ())
AttributeError: 'str' object has no attribute 'loads'
On my server appears to me that the errors are at this location
"Conn.send (get_pressure_and_temperature (request_string))"
"JSON_OBJECT = json.loads (request_string)"
This is my code of the client
import socket
import os
import sys
import json
timestamp = 20160210
hour = 6
latitude = 20
longitude = 20
HOST = '' # The remote host
PORT = 10000 # The same port as used by the server
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
#latitude = raw_input ("latitude: \t" )
#longitude = raw_input ("longitude: \t" )
#s.send(latitude)
#s.send(longitude)
#s.send(string)
string = {"timestamp": timestamp, "hour": hour, "lat": latitude, "long": longitude}
s.send(json.dumps(string))
response = s.recv(1024)
json_object = response.loads(response)
s.close()
print 'Received', repr(json_object)
And of the server is :
Necessary imports
import math
import numpy
import pygrib
import sys
import time
import pressure_temperature
import aux
import socket
import os
import json
args=sys.argv # List of arguments of the comand line
def get_pressure_and_temperature(request_string):
json_object = json.loads(request_string)
print json_object
timestamp = int(json_object["timestamp"])
print timestamp
hour = float(json_object["hour"])
print hour
latitude = float(json_object["lat"])
print latitude
longitude = float(json_object["long"])
print longitude
pressure_temperature_result = pressure_temperature.build_data(timestamp, hour, latitude, longitude)
print "result = ", pressure_temperature_result
return json.dumps(pressure_temperature_result)
HOST = '' # Symbolic name meaning all available interfaces
PORT = 10000 # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)
while True:
conn, cliente = s.accept()
pid = os.fork()
if pid == 0:
s.close()
print 'Connected by', cliente
while True:
request_string = conn.recv(1024)
conn.send(get_pressure_and_temperature(request_string))
if not request_string: break
print "ok"
print "Finalizando conexao com cliente", cliente
#conn.close()
sys.exit(0)
else:
conn.close()
Related
Hello somebody can resolve this problem with arguments.
Problem:raceback (most recent call last):
File "/home/master/PycharmProjects/pythonProject/Final project/server.py", line 33, in <module>
Station_id,Alarm1,Alarm2 = message.split()
ValueError: not enough values to unpack (expected 3, got 0)
Connected by ('127.0.0.1', 34494)
Station_id:123, Alarm1:1, Alarm2:0
can i ignore this message and continue code,its not creation a db for this station.
Process finished with exit code 1
Server code:
import socket
import datetime
import sqlite3
last_date = datetime.datetime.now().strftime('%Y-%m-%d %H:%M')
HOST = "127.0.0.1" # Standard loopback interface address (localhost)
PORT = 5060 # Port to listen on (non-privileged ports are > 1023)
DB = "data.sqlite"
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind((HOST,PORT))
s.listen()
conn,addr = s.accept()
with conn:
print(f"Connected by {addr}")
with sqlite3.connect(DB) as info:
info.execute('''
create table if not exists station_status (
Station_id INTEGER,
last_date TEXT,
Alarm1 INTEGER,
Alarm2 INTEGER,
PRIMARY KEY (station_id));
''')
while True:
data = conn.recv(1024)
message = data.decode()
Station_id,Alarm1,Alarm2 = message.split()
print("Station_id:{}, Alarm1:{}, Alarm2:{}".format(Station_id, Alarm1, Alarm2))
if not data:
break
conn.sendall(data)
Client:
import socket
import sys
import time
HOST = "127.0.0.1"
FILE= "status.txt"
PORT = 5060 # The port used by the server
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((HOST,PORT))
with open(FILE, 'r') as f:
lines = f.readlines()
line = [lines.rstrip() for lines in lines]
print(line)
message = (' '.join(str(i) for i in line))
is_numeric = message.replace(" ", "")
if is_numeric.isnumeric():
data = message.encode()
s.sendto(data,(HOST,PORT))
else:
print("Wrong data")
is_running = False
How can I send selected data frame To client from server. I have a data frame I select specific data frame from it . i got error on client side Error is (TypeError: file must have 'read' and 'readline' attributes) on line pickle.load(received)
Server Side
import socket
import pandas as pd
import pickle
df = pd.read_csv(r"C:\Users\DELL\OneDrive\Desktop\mythesisdataset.csv" ,engine='python',
names=[ 'SBP', 'DBP', 'HEARTRATE', "Temperature" ])
normal_df = (df [ (df.SBP > 120) & (df.DBP > 90) & (df.HEARTRATE < 100) & (df [ 'Temperature' ] < 100) ])
print(normal_df)
normal_df_bytes = pickle.dumps(df)
s = socket.socket()
host = socket.gethostname()
port = 12345
s.bind((host, port))
print("host name:", host, " socket name:", socket)
print("Waiting for Fog-node to connect...")
s.listen()
while True:
c, addr = s.accept()
print('Got connection from', addr, '...')
bytes = c.send(normal_df_bytes)
c.close() # Close the connection
Client side
import socket
import sys
HOST, PORT = "123.123.123.123", 12345
print(sys.argv[0:]);
data = " ".join(sys.argv[1:])
Create a socket
(SOCK_STREAM means a TCP socket)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
# Connect to server and send data
sock.connect((socket.gethostname(), 12345))
sock.sendall(bytes(data + "\n", "utf-8"))
# Receive data from the server and shut down
received = str(sock.recv(1024), "utf-8")
pickle.load(received)
finally:
sock.close()
print("Sent: {}".format(data))
print("Received: {}".format(received))
pickle.load(received) expects a file. Use pickle.loads(received), which excpects bytes
I made a socket connection between a client and server. I set it up so it makes a request for data, but it doesn't receive the data. It throws Traceback (most recent call last): File "C:\...file path...\server.py", line 38, in <module> s1.connect((host1, port1)) ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it, but it sends a response. How can I set it up to receive the message? By the way, it makes a request to the server to read a file.
Server.py:
import json
import socket
import base64
while True:
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind((HOST, PORT))
s.listen()
conn, addr = s.accept()
with conn:
print('Connected by', addr)
while True:
data = conn.recv(1024)
data = repr(data)
data = str(data)
data1 = []
for i in range(len(data)):
data1.append(data[i])
data1[0] = ""
data1[1] = ""
data1[len(data1)-1] = ""
data ="".join(data1).replace("'","\"").replace("~","=")
if (data != ""):
print(data)
data = json.loads(data)
typer = data["type"]
if (typer == 'putreq'):
#Writes to file, there are no bugs here.
else:
host1 = addr[0]
port1 = addr[1]
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s1:
s1.connect((host1, port1))
with open(data["name"], 'r') as userfile:
data1 = userfile.read()
s1.sendall(bytes(base64.b64encode(bytes(data1,'utf-8')),'utf-8'))
s1.close
s.close()
Client.py:
import socket
import sys
import base64
import json
import random
import time
typec = sys.argv[1]
filec = sys.argv[2]
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((HOST, PORT))
s.sendall(bytes(str({"type":'namereq',"name":filec}), "UTF-8"))
data = s.recv(1024)
data = repr(data)
data = str(data)
data1 = []
for i in range(len(data)):
data1.append(data[i])
data1[0] = ""
data1[1] = ""
data1[len(data1)-1] = ""
data ="".join(data1).replace("~","=")
if(data != ''):
print(data)
I think it has to do with the hostname and port being different on the server and the user.
modify this:
else:
host1 = addr[0]
port1 = addr[1]
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s1:
s1.connect((host1, port1))
with open(data["name"], 'r') as userfile:
data1 = userfile.read()
s1.sendall(bytes(base64.b64encode(bytes(data1,'utf-8')),'utf-8'))
s1.close
into this:
else:
with open(data["name"], 'r') as userfile:
data1 = userfile.read()
conn.sendall(bytes(base64.b64encode(bytes(data1,'utf-8')),'utf-8'))
conn.close
you already have a socket connected to that host and port no need to create others (also because i can see that HOST is equal to host1)
The following is complete client , server and sendproc codes:
Client.py
from socket import *
import pickle
import sendproc
import struct
s = socket(AF_INET, SOCK_STREAM) # Create a socket object
host = "192.168.1.4" # Get local machine name
port = 1094 # Reserve a port for your service.
s.connect((host, port))
with open("file.txt",'rb') as f:
print ('file opened')
print('Sending file...')
for data in f:
print(data)
print("MSG sent")
sendproc.send_msg(s, data)
Server.py
from socket import *
import pickle
import sendproc
port = 1094 # Reserve port for service.
s = socket(AF_INET,SOCK_STREAM) # Create a socket object
host = "192.168.1.4" # Get local machine name
s.bind((host, port)) # Bind to the port
s.listen(5)
print('server is listening')
conn,addr = s.accept()
with open("file1.txt",'w') as fb:
print("File downloading\n",fb)
while True:
print("hi")
data = sendproc.recv_msg(conn)
print(data)
if not data:
print("No data")
break
fb.write(data)
fb.flush()
print("Download complete\n")
SendRecieveProcedure.py
import struct
def send_msg(s, msg):
msg2 = struct.pack('>I', len(msg)) + msg
s.send(msg2)
def recv_msg(s):
# Read message length and unpack it into an integer
raw_msglen = s.recv(4)
print(raw_msglen)
if not raw_msglen:
return None
n = struct.unpack('>I',raw_msglen)[0]
# Read the message data
data = ' '
while len(data) < n:
packet = s.recv(n - len(data)).decode("cp437")
if not packet:
return None
data += packet
#print("hwllo",data )
return data
output prints correctly to the console, but if I go open up the file it's only writing starting lines.so what is the problem in code
The problem I'm having is to get a file from the server. Lets say I want to
"get ./testing.pdf" which sends the pdf from the server to the client. It sends but it is always missing bytes. Is there any problems with how I am sending the data. If so how can I fix it? I left out the code for my other functionalities since they are not used for this function.
server.py
import socket, os, subprocess # Import socket module
s = socket.socket() # Create a socket object
host = socket.gethostname() # Get local machine name
#host = ''
port = 5000 # Reserve a port for your service.
bufsize = 4096
s.bind((host, port)) # Bind to the port
s.listen(5) # Now wait for client connection.
while True:
c, addr = s.accept() # Establish connection with client.
print 'Got connection from', addr
while True:
userInput = c.recv(1024)
.... CODE ABOUT OTHER FUNCTIONALITY
elif userInput.split(" ")[0] == "get":
print "inputed get"
somefile = userInput.split(" ")[1]
size = os.stat(somefile).st_size
print size
c.send(str(size))
bytes = open(somefile).read()
c.send(bytes)
print c.recv(1024)
c.close()
client.py
import socket, os # Import socket module
s = socket.socket() # Create a socket object
host = socket.gethostname() # Get local machine name
#host = '192.168.0.18'
port = 5000 # Reserve a port for your service.
bufsize = 1
s.connect((host, port))
print s.recv(1024)
print "Welcome to the server :)"
while 1 < 2:
userInput = raw_input()
.... CODE ABOUT OTHER FUNCTIONALITY
elif userInput.split(" ")[0] == "get":
print "inputed get"
s.send(userInput)
fName = os.path.basename(userInput.split(" ")[1])
myfile = open(fName, 'w')
size = s.recv(1024)
size = int(size)
data = ""
while True:
data += s.recv(bufsize)
size -= bufsize
if size < 0: break
print 'writing file .... %d' % size
myfile = open('Testing.pdf', 'w')
myfile.write(data)
myfile.close()
s.send('success')
s.close