Fuhua Song Fuhua Song - 3 months ago 11
Python Question

testing client- server on the same computer

I am trying to test socket communication on my laptop using python. However, I'm not sure why the connection is not being established? I keep getting error that the target machine is actively refusing connection. I am trying to use the same computer to run both the client and the server portion. The server is running fine but the client is the one not connecting. I think I have the hostname wrong (127.0.0.1) but not sure what Im supposed to be using? I also tried changing the server hostname to (0.0.0.0) and the IPV4 address for the hostname the client was to connect to but that didn't work either. Any help would be appreciated!

My code(server portion):

import socket

comms_socket =socket.socket()
comms_socket.bind(('127.0.0.1', 50000))
comms_socket.listen(10)
connection, address = comms_socket.accept()

while True:
print(connection.recv(4096).decode("UTF-8"))
send_data = input("Reply: ")
connection.send(bytes(send_data, "UTF-8"))


Client portion:

import socket

comms_socket = socket.socket()
comms_socket.connect(('127.0.0.1',50000))

while True:

send_data = input("Message: ")
comms_socket.send(bytes(send_data, "UTF-8"))
print(comms_socket.recv(4096).decode("UTF-8"))

Answer

Your code won't work with python 2.* , because of the differences in input(), raw_input(), bytes, etc. in python 3.* vs python 2.* . You'd have to minimally make the following changes to get it working with python 2.*. Otherwise, use python 3 to run your code:

Server program:

import socket

comms_socket =socket.socket()
comms_socket.bind(('127.0.0.1', 7000))
comms_socket.listen(10)
connection, address = comms_socket.accept()

while True:
    print(connection.recv(4096).decode("UTF-8"))
    send_data = raw_input("Reply: ") # Use raw_input() instead of input()
    connection.send(send_data.encode("UTF-8")) 

Client program:

import socket


comms_socket = socket.socket()
comms_socket.connect(('127.0.0.1',7000))

while True:

    send_data = raw_input("Message: ")
    comms_socket.send(send_data.encode("UTF-8"))
    print(comms_socket.recv(4096).decode("UTF-8"))

If you want to use bytes as intended in your specific usecase, you should use bytesarray instead in python 2.6 or higher. Check this: the bytes type in python 2.7 and PEP-358

Comments