[英]Can a Windows UWP application connect to a websocket server, receive data from it, and display the data?
這是我在 Stackoverflow 上的第一個真正問題。 我目前正在嘗試在我的 UWP(C# 或 C++)應用程序中實現現有的 websocket 服務器。 服務器正在我的筆記本電腦上運行,並且正在接收屏幕截圖數據。 我想將此屏幕截圖數據發送到我的 UWP 應用程序,然后在那里顯示。 我也想要音頻。 有點像遠程桌面情況。 這可能嗎,如果可以,有人可以解釋一下這是如何工作的嗎?
這是我當前截圖發送方法的 python 代碼。 它絕不是完美的,而且非常緩慢。
import cv2 as cv
import numpy as np
import os
import sys
import socket
from PIL import ImageGrab
import pickle
from mss import mss
import struct
from time import time
from windowcapture import WindowCapture
# Client Side Initialization
clientsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
clientsocket.connect(('localhost', 8089))
bounding_box = {'top': 100, 'left':0, 'width':852, 'height':480}
sct = mss()
# Change the working directory to the folder this script is in.
os.chdir(os.path.dirname(os.path.abspath(__file__)))
#not used atm
# initialize the WindowCapture class
# wincap = WindowCapture('FL Studio 20')
loop_time = time()
while(True):
sct_img = sct.grab(bounding_box)
cv2.imshow('screen', np.array(sct_img))
# get an updated image of the game
#screenshot = wincap.get_screenshot()
#cv.imshow('Computer Vision', screenshot)
# debug the loop rate
print('FPS {}'.format(1 / (time() - loop_time)))
loop_time = time()
#send client data
frame = np.array(sct_img)
data = pickle.dumps(frame)
#send message length first
message_size = struct.pack("L", len(data))
#then data
clientsocket.sendall(message_size + data)
# press 'q' with the output window focused to exit.
# waits 1 ms every loop to process key presses
if cv.waitKey(1) == ord('q'):
cv.destroyAllWindows()
break
print('Done.')
quit()
這是服務器端代碼:
import pickle
import socket
import struct
import cv2
HOST = ''
PORT = 8089
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print('Socket created')
s.bind((HOST, PORT))
print('Socket bind complete')
s.listen(10)
print('Socket now listening')
conn, addr = s.accept()
data = b'' ### CHANGED
payload_size = struct.calcsize("L") ### CHANGED
while True:
# Retrieve message size
while len(data) < payload_size:
data += conn.recv(4096)
packed_msg_size = data[:payload_size]
data = data[payload_size:]
msg_size = struct.unpack("L", packed_msg_size)[0] ### CHANGED
# Retrieve all data based on message size
while len(data) < msg_size:
data += conn.recv(4096)
frame_data = data[:msg_size]
data = data[msg_size:]
# Extract frame
frame = pickle.loads(frame_data)
# Display
cv2.imshow('Capture Server Test', frame)
if cv2.waitKey(1) == ord('q'):
cv2.destroyAllWindows()
break
謝謝!
決定通過互聯網傳輸內容是一大步。 這涉及端口轉發、良好的客戶端/服務器設置和實際代碼。 微軟的一些示例讓我開始建立 TCP 連接。
如果您的目標是簡單地傳輸您自己的數據,TCP 可能會起作用。 如果您需要直播或只需要音頻和視頻,也許其他協議更適合您。
一般來說,這在一個答案中無法解釋,因此我建議您研究以下將引導您建立牢固聯系的關鍵事項:
正如我之前提到的,這是非常全球性的,但您的問題也是如此。 從頭開始,問更精確的問題,你就會到達那里。 :)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.