线程无法通过套接字连接

时间:2014-03-06 07:24:45

标签: python multithreading sockets multiprocessing

我是套接字编程的新手,我正在用Python编写一个应用程序,其中将有n个进程通过TCP套接字相互连接。我的想法是每个进程将产生n-1个线程,这些线程将处理套接字的创建以及与其他进程的连接。这是因为每个流程都有自己的黄金和项目,它们将相互“交易”。

我决定使用较低“pid”的进程将成为连接的“服务器”,即侦听和接受客户端连接的进程。在下面的代码中,我随意选择了端口所在的端口号(13000,在这种情况下,但无论数字是多少都会发生错误),并包含一些测试代码以查看连接是否正常工作。但是,当我运行此代码时,我收到多个“连接被拒绝”错误。如果有人能指出我犯了什么错误,那将非常感激!

import socket              
import sys
from multiprocessing import Process
from threading import Thread, Lock

def proc(pid, numprocs):
    money = 1000
    widgets = 0
    mutex = Lock()
    baseport = 13000
    for num in range(numprocs):
        #create threads
        if pid < num:
            t = Thread(target = serverThread, args = (num, pid, numprocs, baseport))
            t.start()
        elif pid > num:
            t = Thread(target = clientThread, args = (num, pid, numprocs, baseport))
            t.start()


def serverThread(num, pid, numprocs, baseport):
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)         
    host = "localhost" 
    port = baseport  + (pid * numprocs) + num

    print 'process ', pid, ' is creating a socket for process ', num, '. host: ', host, ' port: ', port

    s.bind((host, port))
    s.listen(1)

    #testing connections between processes 0 and 2
    if pid == 0 and num == 2:
        while 1:
            client, addr = s.accept()
            client.settimeout(0.1)
            #print 'process ', pid, 'connected to process ', num, ' by ', addr
            print 'money: ', money, ' widgets: ', widgets
            print client.recv(1024)     

def clientThread(num, pid, numprocs, baseport):
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
    host = "localhost"
    port = baseport + (num * numprocs) + pid

    print 'connecting as process ', pid, ' to process ', num, 'host: ', host, ' port: ', port           
    s.connect((host, port))

    #testcode
    if pid == 2 and num == 0:
        for i in range(10):
            s.send('hello')
            s.send(i)

if __name__ == '__main__':
    for pid in range(int(sys.argv[1])):
        Process(target=proc, args=(pid, int(sys.argv[1]))).start()

0 个答案:

没有答案