我使用套接字流,協議Tcp用於服務器和客戶端之間的連接 帶有外部IP地址。 我的問題是我沒有收到客戶端發送的完整數據! I V試圖shearch許多解決方案,我才知道,我要送Data Size
一則發送Actual Data
,這只是我做了什麼,例如:c#使用Tcp協議的套接字流
string Data = ""; // my data here
string Crypted = crypt(Data); // just a method crypting string (work perfectly tested)
byte[] DataBytes = Encoding.Unicode.GetBytes(Crypted);
_ClientSocket.Send(BitConverter.GetBytes(DataBytes.Length),0,4,0);
_ClientSocket.Send(DataBytes,0,DataBytes.Length,0);
而對於接收Somethign就像是:
byte[] uffer;
byte[] BufferData;
int Size;
int Received;
uffer = new byte[4];
while (true)
{
uffer = new byte[4];
Size = _Client.Receive(uffer, 0, 4, 0);
if (Size > 0)
{
if (Size < _Client.ReceiveBufferSize)
{
BufferData = new byte[Size];
}
else
{
BufferData = new byte[_Client.ReceiveBufferSize];
}
Received = _Client.Receive(BufferData, 0, BufferData.Length, 0);
string Msg = Encoding.Unicode.GetString(buffer);
String Data = U.Decrypt(Msg);
}
但我仍然不接收數據,如果我做了,我沒有收到它!
請編輯問題以使用實際顯示問題的代碼(即完整且最小的重新創建)。注1:我過去一直使用這種方法,它已經工作了; 2.請使用正常的.NET命名約定,[SO]語法突出顯示效果會更好(這非常簡單)。 – Richard
在'uffer'中的4個字節的字節,消息在'BufferData'中,但是你解碼'buffer',這在代碼片段的其他地方沒有使用。 –
@Richard多數民衆贊成我的代碼其發行的代碼。 –