My simple client crash everytime it tries to connect to my python socket server

2.9k views Asked by At

My client crash everytime it tries to connect to my python socket server. I dont know why but but my server seams to start up fine then when i start up my client it establishes a connection to the server but it crash direct. Im doing almost as what they say in py socket docs so im wondering if i have missed something or just staring blindly on something easy. Could any one help pls im using python3.4.

server.py

import socket 

host = ''
port = 1010

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
s.bind((host, port)) 
s.listen(1) 
conn, addr = s.accept() 
print ("Connection from", addr) 
while True: 
    databytes = conn.recv(1024)
    if not databytes: break
    print("Recieved: "+(databytes.decode('utf-8')))
    response = input("Reply: ") 
    if response == "exit": 
        break
    conn.sendall(response.encode('utf-8')) 
conn.close()

client.py

import socket 

host = '127.0.0.1'
port = 1010 

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
s.connect((host, port)) 
print("Connected to "+(host)+" on port "+str(port)) 
initialMessage = input("Send: ") 
s.sendall(initialMessage.encode('utf-8'))  

while True: 
 data = s.recv(1024) 
 print("Recieved: "+(data.decode('utf-8')))
 response = input("Reply: ") 
 if response == "exit": 
     break
 s.sendall(response.encode('utf-8')) 
s.close()
1

There are 1 answers

5
Anand S Kumar On BEST ANSWER

There are two issues in your server/client programs.

  1. You server has two accept() calls, before the while loop and inside the while loop , this causes the server to actually wait for two connections before it can start receiving any messages from any client.

  2. The socket.sendall() function takes in bytes not string , so you need to encode the string using some suitable encoding to convert it to bytes , before sending the data . Also , the function - socket.recv() - returns bytes . So you need to decode the bytes data (using the same encoding you used to encode when sending) , so that you can get the correct string back and it can be printed. A suitable encoding can be - utf-8 - but you can use any encoding of you choice.

An example of encoding a string and using sendall() func -

s.sendall(response.encode('utf-8'))

an example of decoding the string when receiving the data -

databytes = conn.recv(1024)
if not databytes: break
data = databytes.decode('utf-8')

You do not neccessarily need to store the decoded value in another variable, you can also directly call the .decode('utf-8') function when printing the data like - print("Recieved: "+(data.decode('utf-8'))) .