我正在尝试从连接到我的服务器的应用程序接收数据,但是它将数据发送为空?
//Receive Data
int received = socket.EndReceive(AR);
byte[] dataBuf = new byte[received];
Array.Copy(_buffer, dataBuf, received);
string ReserveText = Encoding.ASCII.GetString(dataBuf);
//Write to Console if no error appears
Console.WriteLine("Message received from client: " + ReserveText);
目前正在打印从客户端收到的消息:,打印后的'ReserveText'是保留测试显然是空的?上面的代码是我的服务器代码,下面我已经分享了完整的void和客户端中的代码。
Full Void:
public void ReceiveCallback(IAsyncResult AR)
{
Socket socket = (Socket)AR.AsyncState;
string clientIP = socket.RemoteEndPoint.ToString();
try
{
//Receive Data
int received = socket.EndReceive(AR);
byte[] dataBuf = new byte[received];
Array.Copy(_buffer, dataBuf, received);
string ReserveText = Encoding.ASCII.GetString(dataBuf);
//Write to Console if no error appears
Console.WriteLine("Message received from client: " + ReserveText);
string ResponceText = "Testing Response";
byte[] data = Encoding.ASCII.GetBytes(ResponceText);
//socket.BeginSend(data, 0, data.Length, SocketFlags.None, new AsyncCallback(SendCallback), socket);
SendAsync(socket, data, 0, data.Length);
Console.WriteLine("Message sent to client: " + ResponceText);
socket.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback),
socket);
}
catch (Exception)
{
Console.WriteLine("Client Disconnected");
//TODO: DISPOSE THE SOCKET/SESSION FROM _clients
}
}
以下是客户端SENDING到服务器的方法
public static string SendMessageAndReturnResponse(string req)
{
byte[] buffer = Encoding.ASCII.GetBytes(req);
_clientSocket.Send(buffer);
byte[] receivedBuf = new byte[1024];
int rec = _clientSocket.Receive(receivedBuf);
byte[] data = new byte[rec];
Array.Copy(receivedBuf, data, rec);
return Encoding.ASCII.GetString(data);
}