LYrick Ness
LYrick Ness

Reputation: 1

Can we not use socket and threading together to send and receive messages?

I am trying to make a program to interact between client and server using socket and thread. In my program the server is waiting for data and the client sends a data.

But after i used thread so that the data can be asked continuously it gave an error when data is being send or received.

Server

import socket
import threading
import keyboard

HOST = "127.0.0.1"
PORT = 65432

def receive_function(pon):
        while True:
            det = pon.recv(1024)
            if det:
                print(f"\t\t\t\tFriend: {det.decode('utf-8')}")
            else:
                continue

with socket.socket(socket.AF_INET,socket.SOCK_STREAM) as s:
    s.bind((HOST,PORT))
    s.listen()
    print("LisTenING...")
    while True:
        conn, addr = s.accept()
        print(f"Connection Established with {addr} Device")
        x = threading.Thread(target=receive_function, args=(conn,))
        x.start()

Client

import socket
import keyboard
import threading
from time import sleep

HOST = "127.0.0.1"
PORT = 65432

def send_data(s1):
        print("S1 is ",s1)
        s1.send(bytes("oi k xa", 'utf-8'))

with socket.socket(socket.AF_INET,socket.SOCK_STREAM) as s:
    s.connect((HOST,PORT))
    x = threading.Thread(target=send_data, args=(s,))
    x.start()

Error

Exception in thread Thread-1:
Traceback (most recent call last):
  File "E:\Python371\lib\threading.py", line 917, in _bootstrap_inner
    self.run()
  File "E:\Python371\lib\threading.py", line 865, in run
    self._target(*self._args, **self._kwargs)
  File "practice2.py", line 11, in send_data
    s1.send(bytes("oi k xa", 'utf-8'))
OSError: [WinError 10038] An operation was attempted on something that is not a socket

Can anyone give me solution and reason that why i am not able to send and receive data when threading is used.

Upvotes: 0

Views: 345

Answers (1)

Mark Tolonen
Mark Tolonen

Reputation: 178030

The with in the main thread is closing the socket when the with block exits. Instead, open the socket in the thread, or move the with to the thread so it closes after sending.

Option 1:

import socket
import threading

HOST = "127.0.0.1"
PORT = 65432

def send_data():
    s = socket.socket()
    s.connect((HOST,PORT))
    with s:
        print("s is", s)
        s.sendall(b"oi k xa")

x = threading.Thread(target=send_data)
x.start()

Option 2:

import socket
import threading

HOST = "127.0.0.1"
PORT = 65432

def send_data(s):
    with s:
        print("S1 is ",s)
        s.sendall(b"oi k xa")

s = socket.socket()
s.connect((HOST,PORT))
x = threading.Thread(target=send_data, args=(s,))
x.start()

Upvotes: 2

Related Questions