Search code examples
pythonserverclient

try to make a client and server in python to send and receive some thing


this is my code for make a server:

from socket import *
s = socket(AF_INET , SOCK_STREAM)
s.bind(("",9090))
s.listen(1)
print("Server Binding on port 9090 ...\n")
client , addr = s.accept()
print ("Connected to" +str(addr)+'\n')
while True:
    msg = input("Message = ")
    msg2 =client.sendall(msg.encode("utf-8"))
    msg2 = client.recv(1024)
    msg2 = str(msg2)
    print (msg2)

when i run in cmd until i want send a message from client to server i got 'str' error in client: server:

    Server Binding on port 9090 ...

Connected to('192.168.43.16', 4642)

Message = salam

client:

C:\Users\Administrator>python

Python 3.8.2 (tags/v3.8.2:7b3ab59, Feb 25 2020, 23:03:10) [MSC v.1916 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information.

>>> from socket import *

>>> s =socket(2,1)
>>> s.connect(("192.168.43.16",9090))
>>> s.recv(1024)
b'salam'
>>> s.send("salam")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: a bytes-like object is required, not 'str'

Solution

  • Since you are sending bytes, you should encode the message that you are sending to the server. Where you have s.send("salam") it should be s.send("salam".encode('utf-8')).

    I hope it helped.