简体   繁体   中英

Python Socket, send and recv with only one socket

I am going to implement a socket-based client-server application using python. The client sends a file to the server, and the server should get back to the client a response.

This is the code in the server side:

TCP_IP = 'localhost'
TCP_PORT = 9001
BUFFER_SIZE = 1024

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind((TCP_IP, TCP_PORT))
f = open("test_file", 'wb')
while True:
    data = sock.recv(BUFFER_SIZE)
    if not data:
        f.close()
        break
    f.write(data)
f.close()

response = Function("test_file")
self.sock.sendall(response.encode())

And this the code in the client side:

TCP_IP = 'localhost'
TCP_PORT = 9001
BUFFER_SIZE = 1024

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((TCP_IP, TCP_PORT))

f = open("input_file", 'rb')
while True:
    l = f.read(BUFFER_SIZE)
    x = ''
    while (l):
        s.send(l)
        l = f.read(BUFFER_SIZE)
    if not l:
        x = s.recv(10).decode()
        print("Response: ", x)
        f.close()
        s.close()
        break

It works as follow. Client sends the file correctly, and the file is saved in the server side. But when the server tries to get back the response, the client doesn't accept it, If I remove the recv() function on the client, the server sends the response through my network (now I'm working locally), however, if I keep the recv() function. nothing happens, The response is calculated. my understanding is that recv() doesn't accept data? Any idea?

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind((TCP_IP, TCP_PORT))
f = open("test_file", 'wb')
while True:
    data = sock.recv(BUFFER_SIZE)

You are using TCP: Here the server must listen on the server socket and then accept a new connection (which means it gets a new socket) and communicate through this new socket. You cannot simply skip the listen and accept since without these the connect from the client will not work.

One could do such a setup with UDP ( socket.SOCK_DGRAM ) but not TCP, because TCP needs real connections with a handshake involved in connection setup and tear down. UDP instead just transfers single packets.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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