2017-09-22 41 views
1

我試圖使用TcpListener讀入收到的消息。我設立了一個聽衆,並收到一條消息。但是這個消息很奇怪。我得到這樣的:從其他應用程序(我沒有這個應用程序的源代碼)通過https發送c#TcpListener收到消息中的奇怪字符

▬♥♥¡☺?♥♥YÄÂb­ #ù÷"MDòs←ç→.ge ûjò8┼#i(♥→å:À#À'<À%À)[email protected]À À‼/À♦À♫32À+À/oÀ-À1z¢À↕▬‼ÿ☺:▬¶↨↑↓▬¶♠♥♠☺♣♥♣☺♦♥♦☺♦☻☻♥☻☺☻☻ 

消息(是有可能的是,HTTPS是什麼問題?)。無論如何,我設置的聽衆是這樣的:

static void Main(string[] args) 
{ 
    TcpListener listener = new TcpListener(IPAddress.Parse("127.0.0.1"), 11000); 
    Console.WriteLine("Listening..."); 
    listener.Start(); 

    TcpClient client = listener.AcceptTcpClient(); 
    Console.WriteLine("Connection accepted."); 

    Thread t = CreateThread(client, false); 
    t.Start(); 
} 

private static Thread CreateThread(TcpClient client) 
{ 
    Thread t = new Thread(delegate() 
    { 
     byte[] data = new byte[300]; 
     client.Client.Receive(data); 
     Console.WriteLine("Received data: "); 

     string value = Encoding.Default.GetString(data); 
     Console.WriteLine(value); 
    }); 

    return t; 
} 

該消息應該是一個有效的xml樹。我正在使用C#和.NET框架4.5.2。我究竟做錯了什麼?

+2

如果應用程序發送HTTPS請求,爲什麼使用TcpListener? – CodeCaster

+2

https是加密的,**你不希望**自己實現這個。 –

+0

@CodeCaster Tbh我對HTTPS不是很熟悉。你推薦什麼來代替TcpListener? – Therk

回答

0

正如評論所說,您似乎正在嘗試在OSI模型上獲取較低級別的數據。您可以使用HttpClient從您正在收聽的應用程序獲取數據,而不是使用TcpClient。

雖然它取決於您的服務器是什麼以及如何處理請求。

var httpClient = new HttpClient(); 
var response = await httpClient.GetAsync(uri); 

另一種解決方案是在現有的TCP連接上使用StreamReader,下面的問題就是一個例子。雖然解決方案真的取決於你的服務器。

How reading messages from Server? (tcp)

0

如果你調用使用SOAP/XML,然後使用Web服務客戶端的Web服務(添加Web引用到Visual Studio項目)

使用的System.Net。 Http.HttpClient或System.Net.WebClient從Web服務器下載xml文件。

不使用TCP客戶端嘗試解碼加密的網絡流量。