简体   繁体   English

Python TCP sockets 标头

[英]Python TCP sockets headers

I need to create a communication between a client and a server with TCP. But I'd like to send and work with "headers".我需要使用 TCP 在客户端和服务器之间创建通信。但我想发送和使用“标头”。 So from the client I'd like to send a header "COMMAND1" and the server returns me something.所以我想从客户端发送一个 header“COMMAND1”,服务器返回一些东西。

I have the following code:我有以下代码:

Server服务器

import socket
import threading

bind_ip = '0.0.0.0'
bind_port = 9998

server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((bind_ip, bind_port))
server.listen(5)  # max backlog of connections

print ('Listening on {}:{}'.format(bind_ip, bind_port))


def handle_client_connection(client_socket):
    request = client_socket.recv(1024)
    print ('Received {}'.format(request))
    client_socket.send('Response1!'.encode('utf-8'))
    client_socket.close()

while True:
    client_sock, address = server.accept()
    print ('Accepted connection from {}:{}'.format(address[0], address[1]))
    client_handler = threading.Thread(
        target=handle_client_connection,
        args=(client_sock,)  # without comma you'd get a... TypeError: handle_client_connection() argument after * must be a sequence, not _socketobject
    )
    client_handler.start()

Client客户

import socket

hostname, sld, tld, port = 'www', 'integralist', 'co.uk', 80
target = '{}.{}.{}'.format(hostname, sld, tld)

# create an ipv4 (AF_INET) socket object using the tcp protocol (SOCK_STREAM)
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# connect the client
# client.connect((target, port))
client.connect(('0.0.0.0', 9998))

# send some data (in this case a HTTP GET request)
client.send('hi'.encode('utf-8'))

# receive the response data (4096 is recommended buffer size)
response = client.recv(4096)

print (response)

Anyone knows the best way to return "Response1?"任何人都知道返回“Response1”的最佳方式吗? when the header is "COMMAND1" and "Response2!"当 header 是“COMMAND1”和“Response2!”时when the header is "COMMAND2"?当 header 是“COMMAND2”时?

I can't find examples on how to use headers我找不到有关如何使用标头的示例

EDIT: It doesn't have to be "COMMAND1" or "COMMAND2" it can be a "0" or "1", or anything else.编辑:它不一定是“COMMAND1”或“COMMAND2”,它可以是“0”或“1”,或其他任何东西。

If you want to add your own header, you just have to:如果你想添加自己的标题,你只需要:

  1. Make sure your programm finds the start of your message (like, every message beginns "!?&")确保您的程序找到消息的开头(例如,每条消息都以“!?&”开头)

  2. Send your own header-data just after the start-symbol of your message.在消息的开始符号之后发送您自己的标头数据。

  3. Maybe mark the end of your message with something or pass a length in your header.也许用一些东西标记你的消息的结尾或者在你的标题中传递一个长度。

  4. Since TCP will give you a stream of data, it might come to a case, where it just gives you 2 or 3 messages at once.由于 TCP 会给你一个数据流,它可能会遇到这样的情况,它一次只给你 2 或 3 条消息。 You have to separate these messages by yourself (eg by using "?!&" as start of every message).您必须自己分隔这些消息(例如,使用“?!&”作为每条消息的开头)。

You can always create your own protocoll as payload of another protocoll.您始终可以创建自己的协议作为另一个协议的有效负载。 Just as TCP is just payload from the ethernet point of view.就像从以太网的角度来看 TCP 只是有效载荷一样。

You can do something i have done with my program to accept such headers Use pickle library to encode a dict headers and send it through socket.你可以做一些我用我的程序做的事情来接受这样的标题使用pickle库来编码一个dict标题并通过套接字发送它。 Code will look something like this.代码看起来像这样。

import pickle
def handleSocket(headers:dict):
   message = pickle.dumps(headers)
   socket.send(message)

For server side, you will be handling it Gonna initialise the socket recv to 100 kb对于服务器端,您将处理它 Gonna initialize the socket recv to 100 kb

def handleReceivedSocket(socket):
    message:dict = pickle.loads(socket.recv(102400))

Another way to do this.另一种方法来做到这一点。 Is sending a raw json string to the server (just change pickle.dumps , pickle.loads by json.dumps , json.loads But it will be in raw and less secure.正在向服务器发送原始 json 字符串(只需将pickle.dumpspickle.loads更改为json.dumpsjson.loads但它将是原始字符串并且安全性较低。

Last way you can do it is uri encoding.最后一种方法是 uri 编码。 Check w3schools检查w3schools

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM