Home > Software design >  Sending an array through socket
Sending an array through socket

Time:09-10

I am reading two values i.e Data = [8, 10] on the server side and want to send it to the client side but on the client side i receive the data as "810".

Client Side:

import socket

try:
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error as err:
    print("Socket creation failed with error : ", err)

s.connect((socket.gethostname(), 9880))
print("connected to cloud.")

print(time.time(), ":\tSending request")
print(time.time(), ":\tWaiting for cloud's reply")

Data = []
for i in range(0,2):
    c = s.recv(128)      
    c_d = c.decode()
    print("Data: ",c_d)
    Data.append(c_d)

Server Side:

import socket
try:
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error as err:
    print("Socket creation failed with error : ", err)

s.bind((socket.gethostname(), 9880))
s.listen(5)

while True:
  print("Listening for connections ...")
  c, addr = s.accept()
  print("\tGot a connection!\n")


Data = [8, 10]    
for i in Data:
   s.send(str(i).encode())

CodePudding user response:

Try splitting up the numbers of the array you are sending over by including commas and spaces in the data stream. Instead of sending over just i, add a comma string after each value in the array.

import socket
try:
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error as err:
    print("Socket creation failed with error : ", err)

s.bind((socket.gethostname(), 9880))
s.listen(5)

while True:
  print("Listening for connections ...")
  c, addr = s.accept()
  print("\tGot a connection!\n")


Data = [8, 10]    
for i in Data:
   s.send((str(i)   ", ").encode())

CodePudding user response:

In order to send and receive data you should use flask and socketio. The code below shows an example of what I mean. This method, you can send ANY type of data.

client.py:

Note: 'addr' is the address of the server you want to connect so you have to pass that when you are running client.py

import socketio

def connect(addr: str):
    socket_client = socketio.Client()
    socket_client.connect(addr)
    socket_client.send("hello")

    @socket_client.on('message')
    def on_message(msg):
        print('message recieved')
        i = input("Enter a message: ")
        socket_client.send(i)

server.py

from flask_socketio import SocketIO, send
from flask import Flask, request

app = Flask(__name__)

socketio = SocketIO(app, manage_session=False)

@socketio.on('message')
def handleMessage(msg):
    data = ['Resended message', msg]
    send(data, room=request.sid)
    

I hope this answers your question and you have learned something new.

  • Related