How to send a square matrix through sockets in udp? - python

I'm using python 2.7 and i have to send a square matrix between two hosts using socket programming in udp. My code sends a string but not a matrix.
This is my code:
import socket
import thread
import time
import ctypes
matrix = [[1,2],[3,5]]
def c():
#print (file.read())
UDP_IP = "127.0.0.1"
UDP_PORT = 5002
#MESSAGE = "Hello, World!"
print "UDP target IP:", UDP_IP
print "UDP target port:", UDP_PORT
#print ("message:", MESSAGE)
sock = socket.socket(socket.AF_INET, # Internet
socket.SOCK_DGRAM) # UDP
sock.sendto(matrix, (UDP_IP, UDP_PORT))
def s():
UDP_IP = "127.0.0.1"
UDP_PORT = 5002
sock = socket.socket(socket.AF_INET, # Internet
socket.SOCK_DGRAM) # UDP
sock.bind((UDP_IP, UDP_PORT))
while True:
data, addr = sock.recvfrom(1024) # buffer size is 1024 bytes
print "received message:", data
while True:
thread.start_new_thread(c, ())
thread.start_new_thread(s, ())
time.sleep(10)
Also, I found this code online. It sends a matrix but i am unable deserialize it according to my needs (in matrix form as the input). If anyone can help me understand this that would be of much help.
Server end:
import socket, pickle
HOST = "127.0.0.1"
PORT = 50007
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)
conn, addr = s.accept()
print 'Connected by', addr
while 1:
data = conn.recv(4096)
if not data: break
conn.send(data)
conn.close()
Client end
import socket, pickle
HOST = "127.0.0.1"
PORT = 50007
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
arr = [[11111],[1,2,3,4],[1,2,3,4,5,6],[1,2,3,4,5,6]]
data_string = pickle.dumps(arr)
s.send(data_string)
data = s.recv(4096)
data_arr = pickle.loads(data)
s.close()
print 'Received', repr(data_arr)

First you should read from the same port, as you send data. Data has to be send as binary. You can use pickle as in your second example. Don't start server threads over and over again.
import socket
import time
import pickle
import threading
UDP_IP = "127.0.0.1"
UDP_PORT = 5002
def server():
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind((UDP_IP, UDP_PORT))
while True:
data, addr = sock.recvfrom(102400)
matrix = pickle.loads(data)
print "received message:", matrix
def send_matrix(matrix):
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
data = pickle.dumps(matrix)
sock.sendto(data, (UDP_IP, UDP_PORT))
threading.Thread(target=server).start()
matrix = [[1,2],[3,5]]
while True:
send_matrix(matrix)
time.sleep(10)

Related

Python socket.send() not working in if statement

I tried programming a simple console menu which sends the string "screenshot" to the client if I press 1 and so on. Now when I press 1 it stops working and if I press Ctrl+C it just sends empty bytes (b' ').
Here is my Server:
import socket
s = socket.socket()
print ("Socket successfully created")
port = 2345
host = '0.0.0.0'
print ("socket binded to %s" %(port))
s.listen(5)
print ("socket is listening")
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)
choice = input('Choice: ')
if choice == 1:
conn.sendall("screenshot")
s.close()
break
And here the client:
import socket
s = socket.socket()
port = 2345
host = 'xxx.xx.xx.xxx'
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((host, port))
data = s.recv(1024)
print('Received', data)
What can I try next?

The server is not terminated

I'm using threads to have a server listening for both TCP and UDP messages. Here is the code:
from threading import Thread
import time
import socket
Listening_Port = 5005
Listening_IP = "127.0.0.1"
#define UDP listening function
def UDPListen():
BUFFER_SIZE = 1024
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # IPv4, UDP
sock.bind((Listening_IP, Listening_Port))
while True:
data, address = sock.recvfrom(BUFFER_SIZE)
print "UDP Messsage from address: ", address
print "Message: ", data
#define a TCP listening function
def TCPListen():
BUFFER_SIZE = 1024
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # IPv4, TCP
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind((Listening_IP, Listening_Port))
while True:
sock.listen(1)
conn, address = sock.accept()
print "TCP connection from", address
data = conn.recv(BUFFER_SIZE)
print "Mesage: ", data
conn.close()
# main function
def main():
ThreadUDP = Thread(target=UDPListen)
ThreadTCP = Thread(target=TCPListen)
print "Starting Server..."
ThreadUDP.start()
ThreadTCP.start()
print "Server Started!"
if __name__ == "__main__":
main()
The problem is that when I press ctrl + c (even multiple times), the program is not terminated and I should close the console.
I tried something like this for def main(), but it didn't work:
def main():
ThreadUDP = Thread(target=UDPListen)
ThreadTCP = Thread(target=TCPListen)
try:
print "Starting Server..."
ThreadUDP.start()
ThreadTCP.start()
print "Server Started!"
# Hit Break / Ctrl-C to exit
except KeyboardInterrupt:
print('\nClosing')
raise
Updated code according to the solution offered in the answers:
from threading import Thread
import time
import socket
Listening_Port = 5005
Listening_IP = "10.0.0.3"
#define UDP listening function
def UDPListen():
BUFFER_SIZE = 1024
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # IPv4, UDP
sock.bind((Listening_IP, Listening_Port))
while not eve.isSet():
data, address = sock.recvfrom(BUFFER_SIZE)
print "UDP Messsage from address: ", address
print "Message: ", data
#define a TCP listening function
def TCPListen():
BUFFER_SIZE = 1024
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # IPv4, TCP
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind((Listening_IP, Listening_Port))
while not eve.isSet():
sock.listen(1)
conn, address = sock.accept()
print "TCP connection from", address
data = conn.recv(BUFFER_SIZE)
print "Mesage: ", data
conn.close()
# main function
def main():
ThreadUDP = Thread(target=UDPListen)
ThreadTCP = Thread(target=TCPListen)
eve = threading.Event()
print "Starting Server..."
ThreadUDP.start()
ThreadTCP.start()
print "Server Started!"
try:
while True:
eve.wait(2)
except Exception:
eve.set()
if __name__ == "__main__":
main()
but I received an error:
NameError: Global name 'threading' is not defined
the problem you have is that you run your listeners in a thread - meaning that signals caught in the main should somehow signal the threads.
use threading.Event and then in the main function :
eve = threading.Event()
<start your threads>
try:
while True:
eve.wait(2)
except Exception
eve.set()
and in the threads instead of while True use while not eve.isSet():

Python - Send Integer or String to Spark-Streaming

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.

Python, I want to make Multiple Connection Chatting Program

I coded chatting program with socket module.
(Python)
and I saw perfect send and get data.
But I found a problem.
This is my Server.py
import socket
import threading
HOST = '127.0.0.1'
PORT = 9999
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)
conn, addr = s.accept()
print(addr)
def sendmsg():
while True:
data = input()
data = data.encode("utf-8")
conn.send(data)
conn.close()
def getmsg():
while True:
data = conn.recv(1024)
if data is None:
break
else:
data = data.decode("utf-8", "ignore")
print(data)
conn.close()
threading._start_new_thread(sendmsg, ())
threading._start_new_thread(getmsg, ())
while True:
pass
Just on Client can connect with server.
I want to make multiple connection.
So I changed value of s.listen(1) to s.listen(2)
but It doesn't work.
Help me TT
This is client.py
import socket
import threading
HOST = "127.0.0.1"
PORT = 9999
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
def sendMsg():
while True:
data = input()
s.sendall(str.encode(data))
s.close()
def getMsg():
while True:
data = s.recv(1024)
data = data.decode("utf-8")
print(data)
s.close()
threading._start_new_thread(sendMsg, ())
threading._start_new_thread(getMsg, ())
while True:
pass
Thank you.

Trying to send array over socket

Ok so I am trying to send an array over a sockets. The array is the axis of a joy stick so x,y,z,slider.
So then i send it over a socket once and I receive it at the other end and then unpickle it where I get the error
It gives me the error _pickle.UnpicklingError: unpickling stack underflow im not really sure what it means but I have read it is because the array is getting cut off.
Client(Uses Pygame to get joystick axis)
x = j.get_axis(0)
y = j.get_axis(1)
slide = j.get_axis(2)
z = j.get_axis(3)
array = (x, y, slide, z)
send_array = pickle.dumps(array)
and just send the array with socket.send(send_array)
and then I receive and just try to print it for testing purposes.
raw_message = sc.recv(1024)
(data1, data2, data3, data4) = pickle.loads(raw_message)
print (data1)
Thanks
Client:
import socket, pickle
HOST = 'localhost'
PORT = 50007
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
arr = (YOUR ARRAY)
data_string = pickle.dumps(arr)
s.send(data_string)
data = s.recv(4096)
data_arr = pickle.loads(data)
s.close()
print 'Received', repr(data_arr)
Server:
import socket
HOST = 'localhost'
PORT = 50007
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)
conn, addr = s.accept()
print 'Connected by', addr
while 1:
data = conn.recv(4096)
if not data: break
conn.send(data)
conn.close()

Categories

Resources