[英]make client socket wait for server socket with Python
i'm trying make client stay active and wait for a server connection. 我正在尝试使客户端保持活动状态并等待服务器连接。 For the moment if I open the client before the server, it fails because client doesn't find server connection and stops running.
目前,如果我在服务器之前打开客户端,它将失败,因为客户端找不到服务器连接并停止运行。 I have seen similar topics, but they where for c# and Java.
我见过类似的主题,但是它们在c#和Java中使用。 I'm a newbie, so help me guys :)
我是新手,请帮帮我:)
#!/usr/bin/env python
import pyaudio
import socket
import sys
import time
# Pyaudio Initialization
chunk = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 10240
p = pyaudio.PyAudio()
stream = p.open(format = FORMAT,
channels = CHANNELS,
rate = RATE,
input = True,
frames_per_buffer = chunk)
# Socket Initialization
host = ''
port = 50000
size = 1024
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host,port))
# Main Functionality
while 1:
data = stream.read(chunk)
s.send(data)
s.recv(size)
#!/usr/bin/env python
import pyaudio
import socket, ssl
import sys
# Pyaudio Initialization
chunk = 1024
p = pyaudio.PyAudio()
stream = p.open(format = pyaudio.paInt16,
channels = 1,
rate = 10240,
output = True)
# Socket Initialization
host = ''
port = 50000
backlog = 5
size = 1024
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host,port))
s.listen(backlog)
client, address = s.accept()
# Main Functionality
while 1:
data = client.recv(size)
if data:
# Write data to pyaudio stream
stream.write(data) # Stream the recieved audio data
client.send('ACK') # Send an ACK
client.close()
stream.close()
p.terminate()
And one more question, what kind of protocol-python extensions should I use to run the same but with remote connection instead of local)? 还有一个问题,我应该使用哪种协议-python扩展来运行相同的协议,但是要使用远程连接而不是本地连接)? Manny thanks :)
曼尼谢谢:)
You can try something like this: 您可以尝试如下操作:
#!/usr/bin/env python
import pyaudio
import socket
import sys
import time
# Pyaudio Initialization
chunk = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 10240
p = pyaudio.PyAudio()
stream = p.open(format = FORMAT,
channels = CHANNELS,
rate = RATE,
input = True,
frames_per_buffer = chunk)
# Socket Initialization
host = ''
port = 50000
size = 1024
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
connected = False
while not connected:
try:
s.connect((host,port))
connected = True
except Exception as e:
pass #Do nothing, just try again
# Main Functionality
while 1:
data = stream.read(chunk)
s.send(data)
s.recv(size)
As for your second question: This should work on remote connections as well, since you bind to all interfaces with host=''
Just make sure you portforward your router (only server needs to be port forwarded) 至于第二个问题:这也应该适用于远程连接,因为您使用
host=''
绑定到了所有接口host=''
只需确保将端口转发给路由器(仅服务器需要转发端口)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.