我正在开发Mac OS应用程序,因为我想每5秒将图像发送到另一台Mac。我正在后端运行Node.js TCP服务器,并将它们都连接为TCP Client。
我正在尝试将Base64编码字符串发送到服务器,并且服务器正在将数据推送到客户端。
接收代码:
extension SocketCreator: StreamDelegate {
func stream(_ aStream: Stream, handle eventCode: Stream.Event) {
switch eventCode {
case Stream.Event.hasBytesAvailable:
print("new message received")
//readAvailableBytes(stream: aStream as! InputStream)
case Stream.Event.endEncountered:
disconnectFromHost()
case Stream.Event.errorOccurred:
print("error occurred : \(aStream.streamError.debugDescription)")
case Stream.Event.hasSpaceAvailable:
print("has space available")
default:
print("some other event...")
break
}
}
private func readAvailableBytes(stream: InputStream) {
let buffer = UnsafeMutablePointer<UInt8>.allocate(capacity: maxReadLength)
while (stream != NSNull.init())&&stream.hasBytesAvailable {
let numberOfBytesRead = inputStream.read(buffer, maxLength: maxReadLength)
if numberOfBytesRead < 0 {
if let _ = inputStream.streamError {
break
}
}
let reciviedMsg = String(bytesNoCopy: buffer,
length: numberOfBytesRead,
encoding: .ascii,
freeWhenDone: true)
delegate?.scoktDidRecivceNewMessagew(message: reciviedMsg ?? "-NA-")
}
}
}
当我在第二台计算机上接收到base64字符串时,i丢失了一些,而base64无法解码。这可能是什么原因。
如果在使用base64编码字符串发送数据时做错了,那么在不丢失数据的情况下通过TCP对图像进行操作的最佳做法是什么。
这是我收集碎片的方式:
func scoktDidRecivceNewMessage(message: String) {
// print("Recived Command @ cient : \(message)")
if message.contains("data:image/png;base64,") {
hasStartedReadingImage = true
base64ImageFrame = message
}
if hasStartedReadingImage {
if message.contains("**end")
{
hasStartedReadingImage = false
base64ImageFrame.append(message)
var base64 = base64ImageFrame.replacingOccurrences(of: "data:image/jpeg;base64,", with: "")
base64 = base64.replacingOccurrences(of: "**end", with: "")
let nsImage = base64.base64Convert()
DispatchQueue.main.async {
self.imgStremingView.image = nsImage
}
}else
{
base64ImageFrame.append(message)
}
}
}