首页 > 解决方案 > 套接字编程尝试发送字符串并将其反转,然后接收反转的字符串

问题描述

我正在处理一个代码文件,我需要在其中发送一个字符串,接收到该数据,然后将字符串反转并以反转的格式发回。我当前的代码没有达到那个反向点,我不确定为什么或如何弄清楚为什么它根本没有达到那个点。这就是我得到的:

import argparse, socket, sys, threading

try:
    import SocketServer as socketserver
except:
    import socketserver

from threading import Thread

try:
    input_function = raw_input
except:
    input_function = input

class ThreadedTCPRequestHandler(socketserver.BaseRequestHandler):

    def handle(self):
        data = self.request.recv(1024)
        cur_thread = threading.currentThread()
        response = "%s: %s" % (cur_thread.getName(), data)
        self.request.send(response.encode())

class ThreadedTCPServer(socketserver.ThreadingMixIn, socketserver.TCPServer):
    pass

def client(ip, port, message):
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.connect((ip, port))
    encoded_message = message.encode()
    sock.sendall(encoded_message)
    response = sock.recv(1024)
    print("Received: %s" % response)
    sock.close()

# main
if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Send and receive TCP')
    parser.add_argument('-ip_address', help='ip address', default="127.0.0.1")
    parser.add_argument('-p', metavar='PORT', type=int, default=1060,
            help='TCP port (default 1060)')
    args = parser.parse_args()
    addr = args.ip_address
    port = args.p
    """
        The IP address passed in will be the IP address that the client will connect to.
        It has been set to default to the local loopback address of 127.0.0.1 for testing purposes

        The port number will be both the port that the server will listen on, and the port that the client will try to connect to.
    """
    # set up threads for both sending and receiving
    try:
        server = ThreadedTCPServer((addr, port), ThreadedTCPRequestHandler)
        # Start a thread with the server -- that thread will then start one
        # more thread for each request
        server_thread = threading.Thread(target=server.serve_forever)
        # Exit the server thread when the main thread terminates
        server_thread.setDaemon(True)
        server_thread.start()
        print( "Server loop running in thread:"+ server_thread.getName() )
    except:
        # assume it couldn't work because we want to try this script
        # as multiple clients connecting to the same server
        # in this case, the server will have already bound to the port
        # and we can't expect to reuse the port
        print("Server is already running on this port")
        # but we keep on running so that the client can still work

    # Now we have the client connect to the server
    prompt_string = "What data would you like to send to the server?"
    t = input_function(prompt_string)
    while (len(t) > 0):
        client(addr,port,t)
        t = input_function(prompt_string)

    try:
        server.shutdown()
    except:
        pass

这是反向字符串代码:

import socket, sys

def reverse_string_as_data(s):
    return str("".join(list(reversed(s.decode("utf-8"))))).encode()
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #@ create a new TCP socket and assign it to the variable sock
port = int(sys.argv[1])
sock.bind(('', port)) #@ bind the sock to the default IP address on the port specified in the variable port
sock.listen(1) #@ tell sock to queue up at most one waiting connection through the use of listen
while True:
    conn, (addr, port) = sock.accept() #@ conn, (addr, port) should be the result of calling the accept method of sock
    data = conn.recv(1024) #@ receive some data on conn and assign it to data (note that recv returns a tuple - we only care about part and can put the rest in a dummy variable)
    atad = reverse_string_as_data(data)
    conn.sendall(atad) #@ send all of atad on conn
    conn.close() #@ invoke the close method on conn

现在我得到的回应是我在它前面输入了 ab 的字符串,我被困在这本书上,我一直认为这是因为没有足够的帮助。

标签: pythonsocketspython-sockets

解决方案


推荐阅读