Python socket send int

Отправить целые числа через сокеты python

У меня есть целое число, которое я хочу передать через сокет на другой в python. Предположим, что это целое число a = 2. Как отправить это целое число через сокет через соединение. В настоящее время я сделал следующий код:

server_socket.send(str(a)) #Server side b=int(client_socket.recv(512)) #Client side 

но вызов int() дает мне ошибку, говоря, что его не имеет допустимой длины. Я в основном не получаю, какой аргумент следует использовать в методе recv().

Вы отправляете целое число в 4 байта по всей линии, но вы пытаетесь получить 512 байтов, поэтому просто выделяете нераспределенный бит памяти следующим образом:

000000000000000000000000000 [… вырезать кучу больше байтов…]

…. с байтами, которые он получает, поэтому он выглядит так:

F34D5DD20000000000000000000 [… обрезать кучу больше байтов…]

Таким образом, у вас есть 512-байтовый массив байтов, который не может быть преобразован в int. recv (4) или еще лучше использовать протокол, который обрабатывает динамические длины (что является единственным на самом деле стабильным решением этой проблемы, вы не можете ожидать, что recv (4) разрешит проблему).

Если вы используете TCP-соединение, вы должны помнить, что это протокол потоковой передачи и, как таковой, не имеет сообщений фиксированного размера. Это означает, что при вызове recv вы можете получить меньше запрошенного количества байтов, даже меньше того, что было отправлено с помощью одного вызова для send . Вы также можете получить все запрошенные, если было больше вызовов для send .

Читайте также:  Html and round corners

Все это означает, что ваш вызов recv может возвращать только часть строки, которая была отправлена, или больше. В любом случае полученная строка, по-видимому, недействительна как целое число. Чтобы узнать, что вы действительно получаете, вы должны распечатать его.

Источник

Socket module, how to send integer

Solution 3: I found a super light way to send an integer by socket: equally use encode(), decode(), instead of bytes() and str(): Solution 4: In Python 3.7.2 Question: Actually, I want to send integers through the server to client and vice versa. One computer acts as a server to provide a certain service and another computer represents the client side which makes use of this service.

Socket module, how to send integer

I am reading in a value on the client side and want to send that to a server side so it can check if its prime. I’m getting an error because the server is expecting a string

server side

import socket tcpsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) tcpsocket.bind( ("0.0.0.0", 8000) ) tcpsocket.listen(2) (client, (ip,port) ) = tcpsocket.accept() print "received connection from %s" %ip print " and port number %d" %port client.send("Python is fun!") 

client side

import sys import socket tcpsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) num = int(raw_input("Enter number: ")) tcpsocket.connect( ('192.168.233.132', 8000) ) tcpsocket.send(num) 

Error: must be string or buffer, not int.

Never send raw data on a stream without defining an upper level protocol saying how to interpret the received bytes.

You can of course send integers in either binary or string format

    in string format, you should define an end of string marker, generally a space or a newline

val = str(num) + sep # sep = ' ' or sep = `\n` tcpsocket.send(val) 
buf = '' while sep not in buf: buf += client.recv(8) num = int(buf) 
val = pack('!i', num) tcpsocket.send(val) 

Those 2 methods allow you to realiably exchange data even across different architectures

tcpsocket.send(num) accept a string , link to the api, so don’t convert the number you insert to int .

I found a super light way to send an integer by socket:

#server side: num=123 # convert num to str, then encode to utf8 byte tcpsocket.send(bytes(str(num), 'utf8')) #client side data = tcpsocket.recv(1024) # decode to unicode string strings = str(data, 'utf8') #get the num num = int(strings) 

equally use encode(), decode(), instead of bytes() and str():

#server side: num=123 # convert num to str, then encode to utf8 byte tcpsocket.send(str(num).encode('utf8')) #client side data = tcpsocket.recv(1024) # decode to unicode string strings = data.decode('utf8') #get the num num = int(strings) 
>>>i_num = 123 >>>b_num = i_num.to_bytes(2, 'little', signed=False) >>>b_num b'>>reverted = int.from_bytes(b_num, 'little', signed=False) >>>i_num == reverted True 

Socket Programming in Python, Socket programming is a way of connecting two nodes on a network to communicate with each other. One socket(node) listens on a particular

Python Socket Programming Tutorial

This socket programming tutorial will show you how to connect multiple clients to a server using
Duration: 49:43

Socket Programming Using Python

And we have to understand two concept first one is Port numbers and second one is type of
Duration: 17:07

Python Sockets Simply Explained

In this video we learn the fundamentals of socket programming in theory and in Python
Duration: 39:33

How to send integer through socket in python

Actually, I want to send integers through the server to client and vice versa. So that I can apply some operations on them on the client/server side. But whenever I a try to send integers, the server or client gets automatically destroyed even without sending the message. I have also used a while loop but it’s not working as it was supposed to do?

Also, it works fine when I send strings (encoded)

import socket s = socket.socket(socket.AF_INET,socket.SOCK_STREAM) print("--------------->SERVER<-----------------") ip = "127.0.0.1" port = 8080 s.bind((ip,port)) s.listen(2) conn,addr = s.accept() print("CONNECTED WITH THE CLIENT\n") while True: #for sending message temp_msg = input("SERVER - ") message = int(temp_msg.encode()) conn.send(message) #for receiving message rec_msg = conn.recv(1024) print("CLIENT - ",rec_msg, " type = ", type(rec_msg)) 
import socket print("--------->CLIENT<----------------") s = socket.socket(socket.AF_INET,socket.SOCK_STREAM) ip = "127.0.0.1" port = 8080 s.connect((ip,port)) print("CLIENT1 IS CONNECTED TO THE SERVER") while True: #for receiving message rec_msg = s.recv(1024) rec_msg = rec_msg print("SERVER - ", rec_msg," type = ", type(rec_msg)) #for sending message temp_msg = input("CLIENT - ") message = int(temp_msg) s.send(message) 

----> output of client side code after sending the initial message through server.py

I found a very simple method to send integer by converting them to string before sending, and then change back to to the integer format after receiving them through a socket.

You can do this by following the below method.

#server side: num=123 # convert num to str, then encode to utf8 byte tcpsocket.send(str(num).encode('utf8')) #client side data = tcpsocket.recv(1024) # decode to unicode string strings = data.decode('utf8') #get the num num = int(strings) 

Python 3 - Network Programming, The socket Module ; socket_family − This is either AF_UNIX or AF_INET, as explained earlier. ; socket_type − This is either SOCK_STREAM or SOCK_DGRAM. ; protocol

Basic Socket Programming in Python

In general, network services follow the traditional client/server model. One computer acts as a server to provide a certain service and another computer represents the client side which makes use of this service. In order to communicate over the network a network socket comes into play, mostly only referred to as a socket. This kind of socket communication can even be used internally in a computer for inter-process communication (IPC).

This article explains how to write a simple client/server application that communicates via network socket using the Python programming language. For simplicity, our example server only outputs the received data to stdout. The idea behind the client/server application is a sensor in a weather station, which collects temperature data over time and sends the collected data to a server application, where the data gets processed further.

What is a Socket?

A network socket is an endpoint of a two-way communication link between two programs or processes - client and server in our case - which are running on the network. This can be on the same computer as well as on different systems which are connected via the network.

Both parties communicate with each other by writing to or reading from the network socket. The technical equivalent in reality is a telephone communication between two participants. The network socket represents the corresponding number of the telephone line, or a contract in case of cell phones.

Example

In order to make use of the socket functionality, only the Python socket module is necessary. In the example code shown below the Python time module is imported as well in order to simulate the weather station and to simplify time calculations.

In this case both the client and the server run on the same computer. A socket has a corresponding port number, which is 23456 in our case. If desired, you may choose a different port number from the unrestricted number range between 1024 and 65535.

The Server

Having loaded the additional Python socket module an Internet streaming socket is created using the socket.socket class with the two parameters socket.AF_INET and socket.SOCK_STREAM . The retrieval of the hostname, the fully qualified domain name, and the IP address is done by the methods gethostname() , getfqdn() , and gethostbyname() , respectively. Next, the socket is bound to the IP address and the port number 23456 with the help of the bind() method.

With the help of the listen() method the server listens for incoming connections on the specified port. In the while loop the server waits for incoming requests and accepts them using the accept() method. The data submitted by the client is read via recv() method as chunks of 64 bytes, and simply output to stdout. Finally, the current connection is closed if no further data is sent from the client.

# load additional Python module import socket # create TCP/IP socket sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # retrieve local hostname local_hostname = socket.gethostname() # get fully qualified hostname local_fqdn = socket.getfqdn() # get the according IP address ip_address = socket.gethostbyname(local_hostname) # output hostname, domain name and IP address print ("working on %s (%s) with %s" % (local_hostname, local_fqdn, ip_address)) # bind the socket to the port 23456 server_address = (ip_address, 23456) print ('starting up on %s port %s' % server_address) sock.bind(server_address) # listen for incoming connections (server mode) with one connection at a time sock.listen(1) while True: # wait for a connection print ('waiting for a connection') connection, client_address = sock.accept() try: # show who connected to us print ('connection from', client_address) # receive the data in small chunks and print it while True: data = connection.recv(64) if data: # output received data print ("Data: %s" % data) else: # no more data -- quit the loop print ("no more data.") break finally: # Clean up the connection connection.close() 
The Client

Now we will have a look at the client side. The Python code is mostly similar to the server side, except for the usage of the socket - the client uses the connect() method, instead. In a for loop the temperature data is sent to the server using the sendall() method. The call of the time.sleep(2) method pauses the client for two seconds before it sends another temperature reading. After all the temperature data is sent from the list the connection is finally closed using the close() method.

# load additional Python modules import socket import time # create TCP/IP socket sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # retrieve local hostname local_hostname = socket.gethostname() # get fully qualified hostname local_fqdn = socket.getfqdn() # get the according IP address ip_address = socket.gethostbyname(local_hostname) # bind the socket to the port 23456, and connect server_address = (ip_address, 23456) sock.connect(server_address) print ("connecting to %s (%s) with %s" % (local_hostname, local_fqdn, ip_address)) # define example data to be sent to the server temperature_data = ["15", "22", "21", "26", "25", "19"] for entry in temperature_data: print ("data: %s" % entry) new_data = str("temperature: %s\n" % entry).encode("utf-8") sock.sendall(new_data) # wait for two seconds time.sleep(2) # close connection sock.close() 
Running the Server and Client

To run both the server and the client program, open two terminal windows and issue the following commands - one per terminal window and in the following order:

The two figures below show the corresponding output of the example program:

Server socket communication in Python_Figure 1_ Client socket communication in Python_Figure 2_

Conclusion

Writing Python programs that use IPC with sockets is rather simple. The example given above can certainly be extended to handle soemthing more complex. For further information and additional methods you may have a look at some great Python socket programming resources available.

Socket module, how to send integer, In Python 3.7.2 tcpsocket.send(num) accept a string , link to the api, I found a super light way to send an integer by socket:

Источник

Оцените статью