[英]Client server communication via sockets within same file/program in Python?
I need to make a program that communicates within the same program back and forth between client and server, but after following the instructions on: http://woozle.org/~neale/papers/sockets.html it just keeps listening and I see nothing printed. 我需要制作一个在客户端和服务器之间在同一程序之间来回通信的程序,但是按照以下说明进行操作: http : //woozle.org/~neale/papers/sockets.html,它一直在监听,我看到了没有印任何东西。
How do I enable basic client server functionality within the same file? 如何在同一文件中启用基本的客户端服务器功能?
#!/usr/bin/python # This is server.py file
import socket # Import socket module
import random
import os
import time as t
#open socket
s = socket.socket() # Create a socket object
host = socket.gethostname() # Get local machine name
port = random.randint(0,65535) # Reserve a port for your service.
if os.fork() == 0:
#server
s.listen(1)
print 'about to listen'
while 1:
c = s.accept()
cli_sock, cli_addr = c
cli_sock.send("Hello to you! %s" % cli_addr)
elif os.fork() == 0:
t.sleep(1)
#client
print 'in here2'
s.bind((host, port)) # Bind to the port
s.connect((host,port))
s.send("Hello!\n")
print s.recv(8192)
s.close()
You're never going to hit your client code, as you enter an infinite loop right after starting the listener. 启动侦听器后立即进入无限循环,您将永远不会碰到客户代码。 For a toy example like this, you'll need to create 2 socket objects, one for the server and one for the client, then pingpong back and forth between them within your code;
对于像这样的玩具示例,您需要创建2个套接字对象,一个用于服务器,一个用于客户端,然后在代码中在它们之间来回乒乓。 you can't use a serve forever style loop like you are here unless it runs in a parallel thread/process so you don't block execution of the main thread.
除非它在并行线程/进程中运行,否则您不能像在这里那样使用永久服务样式循环,这样就不会阻塞主线程的执行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.