因此,我利用C#中的Socket类设置了一个非常基本的服务器和一个客户端。 我以前做过一个异步的地方,所以我决定尝试一下。
我遇到的问题是,我一直在从服务器向客户端发送数据,但是客户端仅获得第一个,然后就好像它停止监听了。 有什么方法可以继续检查是否有传入的数据,然后只是检查它?
客户
private static Socket _clientSocket;
private static byte[] buffer = new byte[2048];
static void Main(string[] args)
{
Connect();
Console.ReadLine();
}
private static void Connect()
{
try
{
_clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
_clientSocket.BeginConnect(new IPEndPoint(IPAddress.Loopback, 1234), new AsyncCallback(ConnectCallback), null);
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
}
private static void ConnectCallback(IAsyncResult AR)
{
try
{
_clientSocket.EndConnect(AR);
Console.WriteLine("Connected to the server");
_clientSocket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None,
new AsyncCallback(ReceiveCallback), _clientSocket);
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
}
private static void ReceiveCallback(IAsyncResult AR)
{
Socket clientSocket = AR.AsyncState as Socket;
var length = clientSocket.EndReceive(AR);
byte[] packet = new byte[length];
Array.Copy(buffer, packet, packet.Length);
var data = Encoding.ASCII.GetString(packet);
Console.WriteLine("Received " + data);
}
和服务器
private static Socket _clientSocket;
private static byte[] buffer = new byte[2048];
static void Main(string[] args)
{
Connect();
Console.ReadLine();
}
private static void Connect()
{
try
{
_clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
_clientSocket.BeginConnect(new IPEndPoint(IPAddress.Loopback, 1234), new AsyncCallback(ConnectCallback), null);
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
}
private static void ConnectCallback(IAsyncResult AR)
{
try
{
_clientSocket.EndConnect(AR);
Console.WriteLine("Connected to the server");
_clientSocket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None,
new AsyncCallback(ReceiveCallback), _clientSocket);
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
}
private static void ReceiveCallback(IAsyncResult AR)
{
Socket clientSocket = AR.AsyncState as Socket;
var length = clientSocket.EndReceive(AR);
byte[] packet = new byte[length];
Array.Copy(buffer, packet, packet.Length);
var data = Encoding.ASCII.GetString(packet);
Console.WriteLine("Received " + data);
}
答案 0 :(得分:1)
在您的ReceiveCallback中,再次调用BeginReceive以继续接收。