使用Python使客户端套接字等待服务器套接字

时间:2015-06-03 08:55:44

标签: python sockets

我正在尝试让客户端保持活动状态并等待服务器连接。目前,如果我在服务器之前打开客户端,它会失败,因为客户端找不到服务器连接并停止运行。我看过类似的话题,但是对于c#和Java来说。我是新手,所以请帮助我们:)

客户端代码:

#!/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()

还有一个问题,我应该使用什么样的protocol-python扩展来运行相同的远程连接而不是本地?曼尼谢谢:)

1 个答案:

答案 0 :(得分:5)

您可以尝试这样的事情:

#!/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)

至于你的第二个问题:这也适用于远程连接,因为你绑定到host=''的所有接口只需确保你的路由器(仅服务器需要端口转发)