字符串解码问题。 VB.NET到Python通讯程序

String decoding issue. VB.NET to Python communication program

我正在做一个项目,我想在 windows 上的 VB.NET 应用程序(客户端)和 [=29 上的 python 应用程序(服务器)之间建立通信=],这是我设法做到的。

每当我发送一条消息时,客户端应用程序都会将其发送到服务器应用程序(作为字符串),在那里它被转换为 UTF-8。文本已正确转换,但是,每条消息的末尾都有一个额外的字符,并添加了额外的一行。

我的Python代码

import socket
import threading
import datetime


class Server:
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    connections = []

    def __init__(self):
        self.sock.bind(('0.0.0.0', 8521))
        self.sock.listen(1)

    def handler(self, c, a):
        while True:
            currentDT = datetime.datetime.now()
            data = c.recv(1024)
            for connection in self.connections:
                connection.send(data)
                dat = data.decode()
                print(currentDT.strftime("%I:%M:%S %p") + str(data, 'utf-8', 'ignore'))

                if data=='ShutDown':
                    break
            if not data:
                print(str(a[0]) + ':' + str(a[1]), "Disconnected")
                self.connections.remove(c)
                c.close()
                break


    def run(self):
        while True:
            c, a = self.sock.accept()
            cThread = threading.Thread(target=self.handler, args=(c, a))
            cThread.daemon=True
            cThread.start()
            self.connections.append(c)
            print(str(a[0]) + ':' + str(a[1]), "connected")
        c.close()


server = Server()
server.run()

VB.NET代码中负责发送消息的部分

Dim client As TcpClient
Dim sWriter As StreamWriter
'.....
 Private Sub send(ByVal str As String)
    Try
        sWriter = New StreamWriter(client.GetStream)

        sWriter.WriteLine(str)

        sWriter.Flush()
    Catch ex As Exception
        xUpdate("You're not server")
    End Try
End Sub

谢谢!

实际上,进一步考虑,您看到的额外字符可能是回车 return,而额外的行可能是因为末尾的换行符。例如,如果将 "Hello World" 传递给 WiteLine,Python 代码可能将其解释为两行,第一行以回车符 return 结尾,第二行是空字符串。您可能需要做的是调用 Write 而不是 WriteLine 并且如果您正在编写一个包含换行符的 String ,请将所有 CR-LF 对替换为 LF:

Private Sub send(ByVal str As String)
    Try
        sWriter = New StreamWriter(client.GetStream)

        sWriter.Write(str.Replace(ControlChars.CrLf, ControlChars.Lf))

        sWriter.Flush()
    Catch ex As Exception
        xUpdate("You're not server")
    End Try
End Sub

如果要发送多条消息,您可能还需要在除第一条消息之外的所有消息之前写一个 LF。