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

Jean-Paul Calderone exarkun at divmod.com
Fri Aug 22 14:32:27 EDT 2008


On Sat, 23 Aug 2008 02:25:17 +0800, Leo Jay <python.leojay at gmail.com> wrote:
>On Sat, Aug 23, 2008 at 1:58 AM, Jean-Paul Calderone <exarkun at divmod.com> wrote:
>> On Sat, 23 Aug 2008 01:47:23 +0800, Leo Jay <python.leojay at gmail.com> wrote:
>>>
>>> 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
>>>
>>
>> You're connecting and accepting with the same socket.  That's not a very
>> good thing to do.  You're not even reading and writing on the same socket,
>> since you're writing to the socket which you get from accept (if the code
>> could get that far).
>>
>
>not exactly. the socket connecting to port 1 is listening to port 2.
>port 1 and port 2 are not the same.

No - it's just what I said.  create_socket creates one socket and passes
it to read_socket and write_socket.  read_socket calls connect on the
socket it is passed.  write_socket calls accept on the socket it is passed.
So a single socket has connect and accept called on it.  Now, main does
call create_socket twice, so this does happen to two sockets, but it's
broken in each case.

>
>> What are you trying to do?  Why are you connecting and accepting?  Why do
>> you need two threads?
>>
>
>I'm migrating a java module to python. In the java code, after
>creating a socket,
>the code gets an InputStream and an OutputStream from that socket,
>sends and receives data in different threads.
>So I just want to do the same thing. (at least do the same thing
>currently, I don't want to change all related projects at the same
>time.)

Two threads per socket is a bad design. :(

>
>> Have you seen Twisted?  http://twistedmatrix.com/
>>
>
>not yet, but it seems that it's quite a complicated module, isn't it?
>is it possible to get the work done without adopting such a monster? :)
>

It's complicated so that applications using it don't have to be.  It's
easier to write network code with Twisted than with the socket and
threading modules.

Jean-Paul



More information about the Python-list mailing list