>Pre:
我有客户端和服务器。我将一些数据从客户端(win表单)发送到服务器(控制台)。我在客户端上使用它发送数据:
try {
sock = client.Client;
data = "Welcome message from client with proccess id " + currentProcessAsText;
sock.Send(Encoding.ASCII.GetBytes(data));
}
catch
{
// say there that
}
在服务器上,我通过以下方式接收数据:
private void ServStart()
{
Socket ClientSock; // сокет для обмена данными.
string data;
byte[] cldata = new byte[1024]; // буфер данных
Listener = new TcpListener(LocalPort);
Listener.Start(); // начали слушать
Console.WriteLine("Waiting connections [" + Convert.ToString(LocalPort) + "]...");
for (int i = 0; i < 1000; i++)
{
Thread newThread = new Thread(new ThreadStart(Listeners));
newThread.Start();
}
}
private void Listeners()
{
Socket socketForClient = Listener.AcceptSocket();
string data;
byte[] cldata = new byte[1024]; // буфер данных
int i = 0;
if (socketForClient.Connected)
{
string remoteHost = socketForClient.RemoteEndPoint.ToString();
Console.WriteLine("Client:" + remoteHost + " now connected to server.");
while (true)
{
i = socketForClient.Receive(cldata);
if (i > 0)
{
data = "";
data = Encoding.ASCII.GetString(cldata).Trim();
if (data.Contains("exit"))
{
socketForClient.Close();
Console.WriteLine("Client:" + remoteHost + " is disconnected from the server.");
break;
}
else
{
Console.WriteLine("n----------------------n" + data + "n----------------------n");
}
}
}
}
}
服务器启动线程并启动每个线程上的侦听套接字。
问题:
当客户端连接或发送消息时,服务器输出收到的消息 + ~ 900 个空格(因为缓冲区为 1024)。如何获取接收的数据长度并根据需要分配如此多的内存?
根据 MSDN 文章,接收返回的整数是接收的字节数(这是分配给 i 的值)。
如果你把你的while循环改成这样,那么你将得到你正在寻找的值:
int bytesReceived = 0;
while (true)
{
i = socketForClient.Receive(cldata);
bytesReceived += i;
if (i > 0)
{
// same code as before
}
}