Socket模块,如何发送整数

7 投票
4 回答
61819 浏览
提问于 2025-05-11 02:04

我在客户端读取一个数值,想把它发送到服务器端,让服务器检查这个数是不是质数。但是我遇到了一个错误,因为服务器期待的是一个字符串。

服务器端

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!") 

客户端

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)

错误:必须是字符串或缓冲区,而不是整数。

我该怎么解决这个问题呢?

相关文章:

  • 暂无相关问题
暂无标签

4 个回答

2

我找到了一种非常简单的方法来通过套接字发送整数:

#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)

可以使用 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)
4

在 Python 3.7.2 版本中

>>>i_num = 123
>>>b_num = i_num.to_bytes(2, 'little', signed=False)
>>>b_num
b'{\x00'
>>>reverted = int.from_bytes(b_num, 'little', signed=False)
>>>i_num == reverted
True
13

在发送数据时,千万不要直接发送原始数据,而是要先定义一个高级协议,说明如何解读接收到的字节。

当然,你可以选择以整数的形式发送数据,可以是二进制格式,也可以是字符串格式。

  • 如果是字符串格式,你需要定义一个 字符串结束 的标记,通常用空格或者换行符来表示。

    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]
    

这两种方法可以让你在不同的系统之间可靠地交换数据。

2

tcpsocket.send(num) 这个方法需要一个 string 类型的内容,这是相关的文档链接,所以你插入的数字不要转换成 int 类型。

撰写回答