[英]Sockets server and client in the same python script
The below code does not work, when I keep both socket server and client code in the same script file where I run server in the main thread and the client in a separate thread using start_new_thread 当我将套接字服务器和客户端代码都保存在同一脚本文件中时,如果使用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()
If you bind()
to your gethostname()
, you also have to connect to that interface from the client, even if it is on the same computer. 如果
bind()
到gethostname()
,则还必须从客户端连接到该接口,即使该接口位于同一台计算机上。 "localhost"
or "127.0.0.1"
will not work. "localhost"
或"127.0.0.1"
将不起作用。 If you want them to work, either bind()
to them directly, or bind to everything ( "0.0.0.0"
or just an empty string, ""
). 如果您希望它们起作用,则直接将它们
bind()
到它们,或绑定到所有内容( "0.0.0.0"
或只是一个空字符串""
)。
Low-budget test code: 低预算测试代码:
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()
Feel free to experiment with testing the various sock+bind combinations. 随意尝试测试各种袜子+绑定组合。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.