Python socket模块,如何发送整数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33913308/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 14:11:14  来源:igfitidea点击:

Socket module, how to send integer

pythonsockets

提问by johndoe12345

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.

Error: must be string or buffer, not int.

How can I resolve this?

我该如何解决这个问题?

采纳答案by k4ppa

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

tcpsocket.send(num)接受string,到 api 的链接,因此不要将您插入的数字转换为int.

回答by Serge Ballesta

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 stringmarker, generally a space or a newline

    val = str(num) + sep # sep = ' ' or sep = `\n`
    tcpsocket.send(val)
    

    and client side:

    buf = ''
    while sep not in buf:
        buf += client.recv(8)
    num = int(buf)
    
  • in binary format, you should define a precise encoding, structmodule can help

    val = pack('!i', num)
    tcpsocket.send(val)
    

    and client side:

    buf = ''
    while len(buf) < 4:
        buf += client.recv(8)
    num = struct.unpack('!i', buf[:4])[0]
    
  • 在字符串格式中,您应该定义字符串结束标记,通常是空格或换行符

    val = str(num) + sep # sep = ' ' or sep = `\n`
    tcpsocket.send(val)
    

    和客户端:

    buf = ''
    while sep not in buf:
        buf += client.recv(8)
    num = int(buf)
    
  • 在二进制格式中,你应该定义一个精确的编码,struct模块可以帮助

    val = pack('!i', num)
    tcpsocket.send(val)
    

    和客户端:

    buf = ''
    while len(buf) < 4:
        buf += client.recv(8)
    num = struct.unpack('!i', buf[:4])[0]
    

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

这 2 种方法使您甚至可以跨不同的体系结构真正地交换数据

回答by Henning Lee

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():

同样使用 encode()、decode(),而不是 bytes() 和 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)