通过python套接字发送字节序列 [英] Send byte sequence over python socket

查看:81
本文介绍了通过python套接字发送字节序列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个非常基本的服务器(出于实验目的),该服务器侦听端口上的传入连接,并在客户端连接时向客户端发送自定义字节序列.但是,系统提示我输入类型异常:

I am trying to write a very basic server (for experimenting purposes) that listens to incoming connections on a port and when a client connects send a custom byte sequence to the client. However I am prompted with a type exception:

TypeError:不带编码的字符串参数

import socket
import sys

HOST = '127.0.0.1'
PORT = 1337

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

try:
    s.bind((HOST, PORT))
except socket.error as msg:
    sys.exit()

s.listen(10)
conn, addr = s.accept()
print ('Connected with ' + addr[0] + ':' + str(addr[1]))
s.send(bytes('\x01\x02\x03'))
s.close()

我是否需要告诉套接字以ascii格式发送它,或者我做错了什么?

Do I need to tell the socket somehow to send it as ascii or what am I doing wrong?

推荐答案

send 方法需要一个类似字节"的对象,它看起来像您在尝试传递但不是正确使用 bytes 函数.

The send method requires a "bytes-like" object, which it looks like you are trying to pass in but aren't using the bytes function properly.

如果您有实际的二进制数据(如您的示例中所示),则可以直接创建bytes对象:

If you have actual binary data, like in your example, you can just create the bytes object directly:

s.send(b'\x01\x02\x03')

如果您有一个字符串(与Python中的字节不同),则必须将字符串编码为字节.这可以通过 bytes 函数完成,但是您必须告诉它使用哪种编码.通常使用ASCII或UTF-8.

If you have a string (which is not the same as bytes in Python), then you have to encode the string into bytes. This can be done with the bytes function but you have to tell it what encoding to use. Generally ASCII or UTF-8 is used.

s.send(bytes('Hello world', 'ascii'))
s.send(bytes('Hello world', 'utf-8'))

这篇关于通过python套接字发送字节序列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆