服务器已连接,但没有响应TCP套接字编程

时间:2018-05-19 00:30:03

标签: python python-2.7 sockets tcp dht

我实现了一个循环的分布式哈希表,每个对等体知道它的直接后继并与其后继者建立TCP连接,例如,1-> 3-> 4-> 5-> 8- > 1

用户将输入一个4位数字,我们使用我们编写的散列函数将其转换为某个值。例如,用户输入3456,对应的散列值是128.对等3获得来自用户的输入,并将散列值传递给其后继者(4),询问他是否大于散列值。如果没有,后继者将把哈希值传递给它的后继者(5)。重复此操作,直到找到合适的同伴。 (这里,因为8< 128,我们说对等1是我们想要的那个)

现在,我们知道对等体1是我们想要的对等体。然后我们让对等体1与请求对等体3建立TCP连接,并发送3" FIND1,3456,3"当对等体3收到此消息时,它应该打印出来#34;对等体1具有值"

我遇到的问题是,在我发现对等体1是我想要的对象之后,我的对等体1客户端与对等体3服务器建立TCP连接(对等体1客户端表示已建立连接),但是对等体3没有&#39 ; t从对等方1获取任何消息,它有什么问题?

我该如何解决?

感谢您耐心阅读这些内容,请随时询问是否有任何含糊不清的内容:)

#!/usr/bin/python2.7
import sys
import socket
import time
import threading
import re
from collections import defaultdict

successor = defaultdict(dict)

peer = int(sys.argv[1])
successor[1] = int(sys.argv[2])
successor[2] = int(sys.argv[3])

serverName = 'localhost'
peerPort = 50000 + int(peer)
address = (serverName,peerPort)

#-------------proceed input string---------------------------
def getFileNum(name):
    fileValid = re.match('^request ([0-9]{4})$',name) 
    if fileValid is None:
        print 'invalid file!'
        return
    else:
        hashName = fileValid.group(1)
        return hashName
#----------------get request input--------------------------------
def getRequestInput(clientSocketTCP):
    while flag == 0:
            fileName = raw_input()
        hashname = getFileNum(fileName)
        if hashname is not None:
            hashname = re.sub('^(0)*','',hashname)
            hashnum = int(hashname) % 256
            info = 'FILE_REQUEST'+str(hashname) + ','+ str(hashnum) + ','+ str(peer) + ',1'
            clientSocketTCP.send(info)
            print 'File request message for '+ str(hashname) + ' has been sent to my successor.'
    clientSocketTCP.close()
#-------------------send file to successor---------------------------
def sendRequestToS(clientSocketTCP):
    global important
    while flag == 0:
        if important: 
                an = re.match('^FILE_REQUEST([0-9]{4}),',important)
            if an:
                hashname = an.group(1)
                clientSocketTCP.send(important)
                            print 'File request message for '+ str(hashname) + ' has been sent to my successor.'
                important = ''
    clientSocketTCP.close()
#-----------------------find file-------------------------------------
def findF():
    global flag
    global important
    while flag == 0:
        if re.match('^FIND',important):
            obj = re.match('^FIND[0-9]{1,3},([0-9]{4}),([0-9]{1,3})',important)
            n = int(obj.group(2))
            info = important
            ff = threading.Thread(target=clientTCPTemp,args=(n,info))
            ff.start()
            ff.join()
            important = ''


#--------------------set up client temporary---------------------------
def clientTCPTemp(n,info):
    global flag
    clientConn = False
    clientSocketTCP = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    serverPortTCP = 50000 + n
    print serverPortTCP
    while not clientConn:
        try:
            clientSocketTCP.connect((serverName,serverPortTCP))
            clientConn = True
            print "Now client connection works!!!!!"
        except:
            print "fail"
    clientSocketTCP.send(info)
    print info
        print 'A response message, destined for peer '+ str(n) +', has been sent.'
    clientSocketTCP.close()


#--------------------TCP server---------------------------------------
def serverTCP():
    global flag
    global serverSetUp
    global important
    serverSocketTCP = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    serverConn = False
    while not serverConn:
        try:
            serverSocketTCP.bind((serverName,peerPort))
            serverConn = True
            serverSocketTCP.listen(2)
            serverSetUp = 0
            print 'The server is ready to receive'
        except:
            pass
    while flag == 0:
        connectionSocket, addr = serverSocketTCP.accept()
        print 'connect by'+ str(addr)
        threeinfo = connectionSocket.recv(1024)
        print threeinfo
        if re.match('^FILE_REQUEST',threeinfo):
            obj = re.match('^FILE_REQUEST([0-9]{4}),([0-9]{1,3}),([0-9]{1,3}),([01])$',threeinfo)
            if obj is not None:
                filename = obj.group(1)
                hashn = int(obj.group(2))
                peerID = int(obj.group(3))
                endCircle = int(obj.group(4))
                if peer < hashn and endCircle: 
                    print 'File ' +filename +' is not stored here. '
                    important = threeinfo
                    if peer > successor[1]:
                            important = re.sub('1$','0',threeinfo)
                else:
                    print 'File '+ filename+' is here.' 
                    important = 'FIND'+str(peer)+','+ filename +','+ str(peerID)
        elif re.match('^FIND',threeinfo):
            dest = re.match('^FIND([0-9]{1,3}),([0-9]{4})','',threeinfo)
            fromP = dest.group(1)
            fileP = dest.group(2)
            print 'Received a response message from peer '+fromP+', which has the file '+fileP
            connectionSocket.send('i receive from you------------------------')

        print sen
        connectionSocket.send('can you hear me?')
        connectionSocket.close()

#--------------------TCP client----------------------------------------
def clientTCP(n):
    global flag
    global serverSetUp
    global important
    clientConn = False
#   while serverSetUp == 1:
#       pass
    clientSocketTCP = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    serverPortTCP = 50000 + n
    while not clientConn:
        try:
            clientSocketTCP.connect((serverName,serverPortTCP))
            clientConn = True
            print "Now client connection works!!!!!"
        except:
            pass
    try:
        rt = threading.Thread(target=getRequestInput,args=(clientSocketTCP,))
        sr = threading.Thread(target=sendRequestToS,args=(clientSocketTCP,))
        ff = threading.Thread(target=findF,args=())
        rt.start()
        sr.start()              
        ff.start()      
    except:
        print 'thread failed'
    sen = raw_input()
    clientSocketTCP.send(sen)
    m = clientSocketTCP.recv(1024)
    print m
    clientSocketTCP.close()

#----------------start thread---------------------------------
#------adapt from https://www.tutorialspoint.com/python/python_multithreading.html --------
flag = 0
serverSetUp = 1
important = ''
findFile = False
try:
    serTCP = threading.Thread(target=serverTCP,args=())
    cliTCP = threading.Thread(target=clientTCP,args=(successor[1],))
    serTCP.start()
    cliTCP.start()
except:
    print "thread can not be set up"
while flag == 0:
    try:
        pass
    except KeyboardInterrupt:
        flag = 1

0 个答案:

没有答案