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
Related
So I'm making a game with my friend. And i have a client+server code for it.
The server part works fine,
but whenever I run the client, it returns an error(python3.10, win10 64bit):
An established connection was aborted by the software in your host machine
server.py:
import socket
import sys
import threading
import os
import random as rand
HOST = ''
PORT = 7474
os.system('title GunLord server vBETA')
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print('# Socket created')
try:
s.bind((HOST, PORT))
except socket.error as msg:
print('# Bind failed. ')
sys.exit()
print('# Socket bind complete')
s.listen(100)
print('# Socket now listening')
def clientThread(conn, addr, playerID):
global PlayerLocationData
print('# Connected to ' + addr[0] + ':' + str(addr[1]))
try:
while True:
data = conn.recv(1024)
line = data.decode('UTF-8')
clientData = line.split('&')
PlayerLocationData[playerID] = str(clientData[0]) +'.'+str(clientData[1])+'.'+str(clientData[2])
responsePlayerLocationData = ''
for i in range(len(PlayerLocationData)):
responsePlayerLocationData +=PlayerLocationData[i]+'%%'
try:
conn.send(str(responsePlayerLocationData).encode())
except:
PlayerLocationData[playerID] = None
except:
conn.close()
threads = []
global PlayerLocationData
PlayerLocationData = []
while True:
conn, addr = s.accept()
playerID = rand.randint(1, 1000)
t = threading.Thread(target=clientThread(conn, addr, playerID))
t.start()
threads.append(t)
s.close()
client.py:
import socket
import random as rand
import time as t
host = '127.0.0.1'
port = 7474
s = socket.socket()
s.connect((host, port))
global PlayerLocations
PlayerLocations = []
def recvDecoder(recvText):
global PlayerLocations
PlayerLocations = recvText.split('%%')
while True:
testX = rand.randint(1, 10)
testY = rand.randint(1, 10)
testZ = rand.randint(1, 10)
print('test coords: {}, {}, {}' .format(testX, testY, testZ))
s.send('{}&{}&{}'.format(testX, testY, testZ).encode())
data = s.recv(1024)
line = data.decode('UTF-8')
recvDecoder(line)
t.sleep(.3)
Full traceback:
Traceback (most recent call last):
File "C:\Users\---\Desktop\---\---\testClient.py", line 19, in <module>
data = s.recv(1024)
ConnectionAbortedError: [WinError 10053] An established connection was aborted by the software in your host machine
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)
I can send my data through CSV file. First, write my random numbers into CSV file then send it, but is it possible to send it directly?
my socket code:
import socket
host = 'localhost'
port = 8080
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host, port))
s.listen(1)
while True:
print('\nListening for a client at',host , port)
conn, addr = s.accept()
print('\nConnected by', addr)
try:
print('\nReading file...\n')
while 1:
out = "test01"
print('Sending line', line)
conn.send(out)
except socket.error:
print ('Error Occured.\n\nClient disconnected.\n')
conn.close()
spark streaming code:
from pyspark import SparkContext
from pyspark.streaming import StreamingContext
sc = SparkContext("local[2]","deneme")
ssc = StreamingContext(sc, 10)
socket_stream = ssc.socketTextStream("localhost",8080)
random_integers = socket_stream.window( 30 )
digits = random_integers.flatMap(lambda line: line.split(" ")).map(lambda digit: (digit, 1))
digit_count = digits.reduceByKey(lambda x,y:x+y)
digit_count.pprint()
ssc.start()
This is because socket blocks sending the data and never moves on. The most basic solution is to send some amount of data and close the connection:
import socket
import time
host = 'localhost'
port = 50007
i = 0
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host, port))
s.listen(1)
try:
while True:
conn, addr = s.accept()
try:
for j in range(10):
conn.send(bytes("{}\n".format(i), "utf-8"))
i += 1
time.sleep(1)
conn.close()
except socket.error: pass
finally:
s.close()
To get something more interesting check non-blocking mode with timeouts.
attempting message encryption with a basic client to host connection
client code:
import socket
import datetime
import time
import threading
tLock = threading.Lock()
shutdown = False
def receving(name, sock):
while not shutdown:
try:
tLock.acquire()
while True:
data, addr = socket.recvfrom(1024)
print (str(data))
except:
pass
finally:
tLock.release()
host = '127.0.0.1'
port = 0
server = ('127.0.0.1',5000)
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind((host, port))
s.setblocking(0)
rT = threading.Thread(target=receving, args=("RecvThread",s))
rT.start()
alias = input("Name: ")
IP=int(socket.gethostbyname(socket.gethostname()).replace(".","5"))
time=(int(datetime.datetime.now().strftime("%Y%m%d%H%M%S")))
qw=(int(str((time)+(IP))))
a=int("934")
b=int("346")
c=int("926")
d=int("9522")
e=int("7334")
f=int("5856")
g=int("2432")
h=int("2027")
i=int("7024")
j=int("828")
k=int("798")
m=int("593")
n=int("662")
l=int("5950")
o=int("357")
p=int("506")
q=int("237")
r=int("98")
s=int("372")
t=int("636")
u=int("553")
v=int("255")
w=int("298")
x=int("8822")
y=int("458")
z=int("657")
space=("633")
msg=input("")
msg=msg.replace("a",(str(a)))
msg=msg.replace("b",(str(b)))
msg=msg.replace("c",(str(c)))
msg=msg.replace("d",(str(d)))
msg=msg.replace("e",(str(e)))
msg=msg.replace("f",(str(f)))
msg=msg.replace("g",(str(g)))
msg=msg.replace("h",(str(h)))
msg=msg.replace("i",(str(i)))
msg=msg.replace("j",(str(j)))
msg=msg.replace("k",(str(k)))
msg=msg.replace("m",(str(m)))
msg=msg.replace("n",(str(n)))
msg=msg.replace("l",(str(l)))
msg=msg.replace("o",(str(o)))
msg=msg.replace("p",(str(p)))
msg=msg.replace("q",(str(q)))
msg=msg.replace("r",(str(r)))
msg=msg.replace("s",(str(s)))
msg=msg.replace("t",(str(t)))
msg=msg.replace("u",(str(u)))
msg=msg.replace("v",(str(v)))
msg=msg.replace("w",(str(w)))
msg=msg.replace("x",(str(x)))
msg=msg.replace("y",(str(y)))
msg=msg.replace("z",(str(z)))
msg=msg.replace(" ",(str(space)))
print(msg)
msg=int(msg)
msg=int(msg)*(qw)
print(msg)
fileb=open("key.txt","w")
filec=fileb.write(str(qw))
fileb.close()
file=open("msg decrypt.txt","w")
filea=file.write(str(msg))
file.close()
msg=(str(e)(msg))
print(IP)
print(qw)
if msg != 'q':
if msg != '':
s.sendto(alias.encode() + ": ".encode() + (str(msg).encode)(), server)
tLock.acquire()
msg = input(alias + "-> ")
tLock.release()
shudown = True
rT.join()
s.close()
host code:
import socket
import time
host = '127.0.0.1'
port = 5000
clients = []
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind((host,port))
s.setblocking(0)
quitting = False
print ("Server Started.")
while not quitting:
try:
data, addr = s.recvfrom(1024)
if "Quit" in str(data):
quitting = True
if addr not in clients:
clients.append(addr)
print (time.ctime(time.time()) + str(addr) + ": :" + str(data))
for client in clients:
s.sendto(data, client)
except:
pass
s.close()
Im struggling as my poor excuse of a encryption is mostly numbers so therefore when im sending using the sendto function only uses str`s or so I think?
either way I get the error:
Traceback (most recent call last):
File "H:\client 2.py", line 103, in <module>
msg=(str(e)(msg))
TypeError: 'str' object is not callable
If msg is an index you should write :
msg = str(e)[msg]
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