Unable to recieve python socket data

Viewed 27

I have two python files: A server and a client. I have the server listening, and the client is supposed to send a simple message, however, the server is not reserving said message.

server.py:

# import socket module
from socket import *
enter code hereimport socket
import sys  # In order to terminate the program
serverSocket = socket.socket(AF_INET, SOCK_STREAM)

serverSocket.bind(('', 9090))
serverSocket.listen(5)

while True:
# Establish the connection
print('Ready to serve...')
connectionSocket, addr = serverSocket.accept()
try:
    print('test')
    message = serverSocket.recv(1024)
    filename = message.decode('utf-8')
    print("filename is" + filename)
    f = open(message)
    outputdata = f.read().replace('\n', '')
    print("about to send file contents")
    for i in range(0, len(outputdata)):
        connectionSocket.send(outputdata[i].encode('utf-8'))
    connectionSocket.send("\r\n".encode())
    connectionSocket.close()
except IOError:
    connectionSocket.send("file not found".encode('utf-8'))
    # Close client socket
    connectionSocket.close()


serverSocket.close()
sys.exit()  # Terminate the program after sending the corresponding data

Client.py

from socket import *
serverPort=9090
serverName=""
clientSocket=socket(AF_INET,SOCK_STREAM)
clientSocket.connect((serverName,serverPort))
sendValue="file.txt"
clientSocket.send(sendValue.encode('utf-8'))
clientSocket.close()

My server will output "Ready to serve..." and "test" but will not output anything else.

1 Answers

for the server, you should recv from connectionSocket not from serverSocket.

i would also recommend you remove the while True and try/except at least while you're developing/debugging so you can clearly see the error messages

p.s. look into "multithreading" and how to accept multiple clients in python

Related