How to read and write the same socket in different threads?

Leo Jay python.leojay at gmail.com
Fri Aug 22 13:47:23 EDT 2008


I'd like to read and write the same socket in different threads.
one thread is only used to read from the socket, and the other is only
used to write to the socket.
But I always get a 10022 'Invalid argument' exception. Anyone knows why?

I'm using windows xp.

my source code is here:
http://pastebin.com/m23e633a2

and the stack trace is:
C:\WINDOWS\system32\cmd.exe /c python "main.py"
Exception in thread Thread-1:
Traceback (most recent call last):
  File "c:\Python25\lib\threading.py", line 486, in __bootstrap_inner
    self.run()
  File "c:\Python25\lib\threading.py", line 446, in run
    self.__target(*self.__args, **self.__kwargs)
  File "main.py", line 7, in read_socket
    sock.connect(('127.0.0.1', remoteport))
  File "<string>", line 1, in connect
error: (10022, 'Invalid argument')

Exception in thread Thread-3:
Traceback (most recent call last):
  File "c:\Python25\lib\threading.py", line 486, in __bootstrap_inner
    self.run()
  File "c:\Python25\lib\threading.py", line 446, in run
    self.__target(*self.__args, **self.__kwargs)
  File "main.py", line 7, in read_socket
    sock.connect(('127.0.0.1', remoteport))
  File "<string>", line 1, in connect
error: (10022, 'Invalid argument')


If i replace the 'args' in line 39 with '(socket(), remoteport)', which means
use a different socket to connect to the remote port, the program works.
But if the first element of the tuple is 's', the program doesn't work.

Is it possible to read and write the same socket in different threads?

Thanks in advance.

-- 
Best Regards,
Leo Jay



More information about the Python-list mailing list