0

I am currently working on my assignment and I am using python socket to connect through terminal. However, I encountered a problem where after I send my message to the server and try to receive its reply, it kind of hangs. My codes are as follows:

import socket
import sys
import md5
import re

hostname = "cs2107.spro.ink"
ip = socket.gethostbyname(hostname)
port = 9000
server_address = (ip, port)
bufferSize = 1024

# Socket connection
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print >>sys.stderr, 'connecting to %s port %s' % server_address
s.connect((ip, port))

try: 
    while True:
        data = s.recv(bufferSize)
        if not data:
            break 

        print data

        regex = re.compile(r'\n([0-9a-fA-F]+)(?:\n)', re.I | re.S | re.M)
        checkHex = re.findall(regex, data)

        if len(checkHex) != 0:
            receiveHex = str(checkHex).strip("['']")
            decode = receiveHex.decode()

            m = md5.new()
            m.update(decode)
            hexReply = m.hexdigest()
            s.sendall(hexReply.encode())
            print hexReply


finally:
    print >>sys.stderr, 'closing socket.....'
    s.close()

The output is shown in the link: output. After I kill it, it says the most recent call is `data = s.recv(bufferSize) link: after killing the terminal. Anyone have any idea how to solve this? Appreciate your help!

Shaoz
  • 3
  • 4
  • Maybe the server sends nothing to your socket, and it keeps waiting forever? First try to send something and then wait for the response. Also you can define a timeout for receiving. – Szabolcs Apr 06 '17 at 19:44
  • the server will check whether the hashed hex string is correct, if correct it will send another hex encoded byte string and the process goes on for 500 times.. if wrong, it will end immediately. It works when I use netcat in the terminal but somehow it doesnt work when i use socket.. – Shaoz Apr 06 '17 at 19:53
  • I tried sending something in the middle and got the same issue – Shaoz Apr 06 '17 at 19:53
  • But you didn't send, first you try to recv, I don't know how is your server configured but I guess it just waits for you to send something before you can recv from. – Szabolcs Apr 06 '17 at 19:56
  • if you click on the output link, the server first send the instructions after that I am suppose to decode the hex encoded byte string, after that use md5 to hash it and send back the hash in hex encoded format – Shaoz Apr 06 '17 at 20:02
  • Managed to solve it! I didn't include \r\n to my reply – Shaoz Apr 06 '17 at 20:08

1 Answers1

0

The line s.recv(bufferSize) is still waiting for some incoming data from the server. However the server sends nothing more than what you see. Try to reply to the server with your hexReply variable and see what happens. Just insert s.send(hexReply + "\r\n") after the print statement.

Thyrst'
  • 2,253
  • 2
  • 22
  • 27