套接字服务器和客户端在相同的python脚本中

时间:2018-07-26 11:28:46

标签: python sockets

当我使用 start_new_thread 将套接字服务器和客户机代码都保存在同一脚本文件中(在主线程中运行服务器,客户机在单独的线程中运行)时,以下代码不起作用>

import socket, sys
from thread import *

host = socket.gethostname()
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
    s.bind((host, 8888))
except socket.error as msg:
    print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
    sys.exit()
s.listen(10)

def clientthread(conn):
    conn.send('Welcome to the server. Type something and hit enter\n')
    while True:
        data = conn.recv(1024)
        reply = 'OK...' + data
        if not data:
            break
        conn.sendall(reply)
    conn.close()

while 1:
    conn, addr = s.accept()
    print 'Connected with ' + addr[0] + ':' + str(addr[1])
    start_new_thread(clientthread ,(conn,))
s.close()

1 个答案:

答案 0 :(得分:0)

如果您bind() gethostname()"localhost"也必须从客户端连接到该接口,即使该接口位于同一台计算机上。 "127.0.0.1"bind()将不起作用。如果您希望它们起作用,请直接"0.0.0.0"绑定到它们,或绑定到所有内容(""或只是一个空字符串from _thread import * import socket,time def client(): print("Thread starts") time.sleep(1) print("Thread connects") sock=socket.create_connection((socket.gethostname(),8888)) #sock=socket.create_connection(("localhost",8888)) print("Thread after connect") sock.sendall(b"Hello from client") sock.close() print("Thread ends") serv=socket.socket() serv.bind((socket.gethostname(),8888)) #serv.bind(("localhost",8888)) #serv.bind(("0.0.0.0",8888)) #serv.bind(("",8888)) serv.listen(10) start_new_thread(client,()) print("Before accept") s,c=serv.accept() print("After accept "+c[0]) print("Message: "+s.recv(1024).decode("ASCII")) s.close() serv.close() )。

低预算测试代码:

const browser = await puppeteer.launch({headless: true, args:['--no-sandbox']});

可以随意尝试测试各种袜子+绑定组合。