我一直在寻找问题,但这些都是文件。
我的问题是:
如何在一个连接中发送/接收大字节(约1-2MB)?
客户端:
while($timecard_record = mysqli_fetch_assoc($timecard_data_results))
{
echo $timecard_record['company_id'] . $timecard_record['task_name'] .$timecard_record['task_start_time'];
echo " " . $iteration . "<br>";
$iteration++;
}
服务器:
TcpClient tcpclnt = new TcpClient();
var result = tcpclnt.BeginConnect(User.IP, User.Port, null, null);
var success = result.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(3));
if (!success)
{
return "Failed to connect!";
}
Stream stm = tcpclnt.GetStream();
UTF8Encoding asen = new UTF8Encoding();
msg = Encrypter.EncryptData(msg);
byte[] ba = asen.GetBytes(msg);
stm.Write(ba, 0, ba.Length); // Switch this to?
SOLUTION:
服务器代码,花了我一点时间让它变得很酷:
System.Net.Sockets.Socket s = myList.AcceptSocket();
byte[] b = new byte[3000000];
int k = s.Receive(b); // Switch this to?
string message = Encoding.UTF8.GetString(b, 0, k);
客户端代码,它运行良好!:
System.Net.Sockets.Socket s = myList.AcceptSocket(); // Accept the connection
Stream stream = new NetworkStream(s); // Create the stream object
byte[] leng = new byte[4]; // We will put the length of the upcoming message in a 4 length array
int k2 = s.Receive(leng); // Receive the upcoming message length
if (BitConverter.IsLittleEndian)
{
Array.Reverse(leng);
}
int upcominglength = (BitConverter.ToInt32(leng, 0)); // Convert it to int
byte[] b = ByteReader(upcominglength, stream); // Create the space for the bigger message, read all bytes until the received length!
string message = Encoding.UTF8.GetString(b, 0, b.Length); // Convert it to string!
internal byte[] ByteReader(int length, Stream stream)
{
byte[] data = new byte[length];
using (MemoryStream ms = new MemoryStream())
{
int numBytesRead;
int numBytesReadsofar = 0;
while (true)
{
numBytesRead = stream.Read(data, 0, data.Length);
numBytesReadsofar += numBytesRead;
ms.Write(data, 0, numBytesRead);
if (numBytesReadsofar == length)
{
break;
}
}
return ms.ToArray();
}
}