套接字编程python,线程出乎意料的结果?

时间:2016-03-14 18:29:29

标签: python multithreading sockets

我正在尝试在服务器上处理结果,直到客户端按下" 6" 。

1.我从客户端向服务器发送关于该做什么的选择。(假设他按1 - 要求搜索一个单词)

2客户端被提示输入单词。

3服务器搜索并相应地返回true或false。

再次向客户提供选择。

现在程序在第一次迭代后暂停。客户端没有执行" ch = raw_input(" ENTER choice")"永远。

可能有什么问题?

server.py

import socket
import thread

def search(key):
    f=open("sample.txt","r")
    data =f.read()
    words = data.split()
    for word in words:
        print (word)
        if word == key:
            f.close()
            return True
    f.close()
    return False




def single_client(conn,addr):
    print ("accepted connection from",addr)
    while True:
        conn.send("1. Search a word Example : ''Python' \n 2. Count its occurrence \n 3. Position of a word\n 4. Find a word for maximum length\n 5 Count the lines \n 6. Exit \n")
        print ("sent choices")
        choice = int(conn.recv(1024))
        print (choice)
        if choice==1:
            key =conn.recv(1024)
            print (key)
            conn.send(str(search(key)))
        if choice == 6:
            print("conn terminated with ",addr)
            return 

host= socket.gethostname()
port =12345

s =socket.socket()

s.bind((host,port))

s.listen(5)

while True:
    conn,addr =s.accept()
    thread.start_new_thread(single_client,(conn,addr,))


conn.close()
s.close()

client.py

import socket

host = socket.gethostname()
port = 12345

s = socket.socket()
s.connect((host,port))

while True:
    print(s.recv(1024))

    ch=raw_input("ENTER choice")
    print ("trying"+ch )
    s.send(ch)
    ch = int(ch)
    if ch == 1:
        s.send(raw_input("ENTER string"))
        print(s.recv(1024))

    if ch ==6:
        break



s.close()

0 个答案:

没有答案