user1050619
user1050619

Reputation: 20916

Python socket connection example

Im writing a simple socket program but get the below error -

Traceback (most recent call last):
  File "C:\Users\ANAND\workspace\Python_Scratch\Scratch\sockettest.py", line 16, in <module>
    print('Received message == ',s.recv(50))
socket.error: [Errno 10057] A request to send or receive data was disallowed because the socket is not connected and (when sending on a datagram socket using a sendto call) no address was supplied

socketserver.py

import socket

s = socket.socket()

host = socket.gethostname()

port = 1234

s.bind((host, port))

s.listen(5)

while True:
    c, addr = s.accept()
    print('Got connection from', addr)
    print('Received message == ',s.recv(50))
    c.send('Thank you for connecting')
    c.close()

socketclient.py

import socket
from time import sleep
s = socket.socket()

host = socket.gethostname()

port = 1234

s.connect((host, port))

sleep(10)
s.sendall("Hello!! How are you")
print(s.recv(1024))

Upvotes: 0

Views: 1970

Answers (1)

unutbu
unutbu

Reputation: 880887

In socketserver.py, use c.recv, not s.recv to receive bytes from the connection:

print('Received message == ', c.recv(50))

Also note that only bytes can be sent through a socket. Therefore, if you are using Python3, be sure to send bytes not strs:

c.send(b'Thank you for connecting')
s.sendall(b"Hello!! How are you")

import multiprocessing as mp
import socket
import time

def basic():
    sproc = mp.Process(target=server)
    sproc.daemon = True
    sproc.start()
    time.sleep(.5)
    client()
    sproc.join()

def server():
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    host = socket.gethostname()
    port = 1234
    s.bind((host, port))
    s.listen(5)
    c, addr = s.accept()
    print('Got connection from {}'.format(addr))
    print('Received message == {}'.format(c.recv(50).decode('ascii')))
    c.send(b'Thank you for connecting')
    c.close()

def client():
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    host = socket.gethostname()
    port = 1234
    s.connect((host, port))
    time.sleep(1)
    s.sendall(b"Hello!! How are you")
    print(s.recv(1024).decode('ascii'))
    s.close()

basic()

yields

Got connection from ('127.0.0.1', 48158)
Received message == Hello!! How are you
Thank you for connecting

Upvotes: 1

Related Questions