Python套接字调用main.py中的server.py和client.py

时间:2018-08-21 09:48:13

标签: python tcpclient tcpserver tcpsocket

我的问题是,如何在main方法中依次调用服务器和客户端?

问题是python调试器在等待并被吸引到调用服务器的行中(阻塞了调用客户端的行)。

我尝试了穿线,但是没有用。感谢您的关注。

重要提示:以下代码使用Python2

主要python文件:

import xClient
import xServer
import threading

tempServer=xServer

tempClient=xClient

thrMain = threading.Thread(target=tempServer.innerClient.Main())
thrMain.start()
thrMain.join()

tempClient.innerClient.Main()

xClient.py:#标准客户端代码并且可以正常工作

import socket
import time

class innerClient:
    def Main():
        time.sleep(2)
        host = '127.0.0.1'
        port = 12345
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.connect((host, port))
        message = "test message"
        while True:
            s.send(message.encode('ascii'))
            data = s.recv(1024)
            print('Received from the server :', str(data.decode('ascii')))


            ans = raw_input('Continue(y/n) :')
            if ans == 'y':
                continue
            else:
                break
        s.close()

xServer.py:#标准服务器代码,可以正常工作

import socket
import threading
class innerServer:
    print_lock = threading.Lock()

    # thread fuction
    def threaded(c):
        while True:
            data = c.recv(1024)
            if not data:
                print('See you later')
                print_lock.release()
                break
            data = data[::-1]
            c.send(data)
        c.close()

    def Main():
        host = ""
        port = 12345
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.bind((host, port))
        print("socket binded to post", port)
        s.listen(5)
        print("socket is listening")
        while True:
            c, addr = s.accept()
            print_lock.acquire()
            print('Connected to :', addr[0], ':', addr[1])

            thr = threading.Thread(target=threaded, args=(c,))
            thr.start()
            thr.join()
        s.close()

TCP Socket Diagram

0 个答案:

没有答案