I've been reading about Python - Network Programming and tried the code.
Looking at the print statement without parentheses, this code is meant for Python 2.
Since I'm using Python3, I've modified it.
Here is the updated code.
server.py
#!/usr/bin/python # This is server.py file
import socket # Import socket module
s = socket.socket() # Create a socket object
host = socket.gethostname() # Get local machine name
port = 12345 # Reserve a port for your service.
s.bind((host, port)) # Bind to the port
s.listen(5) # Now wait for client connection.
while True:
c, addr = s.accept() # Establish connection with client.
print('Got connection from', addr)
c.send('Thank you for connecting')
c.close() # Close the connection
client.py
#!/usr/bin/python # This is client.py file
import socket # Import socket module
s = socket.socket() # Create a socket object
host = socket.gethostname() # Get local machine name
port = 12345 # Reserve a port for your service.
s.connect((host, port))
print(s.recv(1024))
s.close() # Close the socket when done
Then I run both codes as instructed in the tutorial.
Following would start a server in background. $ python server.py &
Once server is started run client as follows: $ python client.py
This would produce following result −
Got connection from ('127.0.0.1', 48437) Thank you for connecting
However, the output that I'm getting is slightly different.
Initially I ran python server.py
. Nothing happened.
Once I executed python client.py
, I'm getting the following error.
user@linux:~$ python server.py
Got connection from ('127.0.0.1', 59546)
Traceback (most recent call last):
File "server.py", line 16, in <module>
c.send('Thank you for connecting')
TypeError: a bytes-like object is required, not 'str'
user@linux:~$
user@linux:~$ python client.py
b''
user@linux:~$
What's wrong with the codes and how to fix it?