Я новичок в программировании сокетов и хочу узнать больше. Недавно я столкнулся с проблемой, когда моя программа не будет повторно подключаться к тому же сокету, если я не использую функцию socket.beginconnect. Я попытался перенести его, но он, похоже, не анализирует полученные пакеты. Может кто-нибудь сказать мне, что я делаю не так?
Я хочу, чтобы он пытался постоянно переподключаться к серверу, если он когда-либо был отключен или серверное приложение закрыто.
public static void ConnectToServer()
{
int attempts = 0;
while (!SocketClient.ClientSocket.Connected)
{
try
{
attempts++;
Console.WriteLine("Connection attempt " + attempts);
// Change IPAddress.Loopback to a remote IP to connect to a remote host.
var endPoint = new IPEndPoint(IPAddress.Parse("no ip for u"), 1712);
var args = new SocketAsyncEventArgs { RemoteEndPoint = endPoint };
SocketClient.ClientSocket.Connect(endPoint);
//autoEvent.WaitOne();
break;
}
catch (SocketException)
{
return;
}
}
Console.WriteLine("Connected");
SocketClient.ClientSocket.BeginReceive(SocketClient.buffer, 0, SocketClient.BUFFER_SIZE, SocketFlags.None, ReceiveCallback, SocketClient.ClientSocket);
}
public static void RequestLoop()
{
Console.WriteLine(@"<Type ""exit"" to properly disconnect client>");
while (true)
{
SendRequest();
ReceiveResponse();
}
}
/// <summary>
/// Close socket and exit program.
/// </summary>
public static void Exit()
{
SocketClient.ClientSocket.Shutdown(SocketShutdown.Both);
SocketClient.ClientSocket.Close();
// Environment.Exit(0);
}
private static void SendRequest()
{
Console.Write("Send a request: ");
string request = Console.ReadLine();
SendString(request);
if (request.ToLower() == "exit")
{
// Exit();
}
}
/// <summary>
/// Sends a string to the server with ASCII encoding.
/// </summary>
private static void SendString(string text)
{
byte[] buffer = Encoding.ASCII.GetBytes(text);
SocketClient.ClientSocket.Send(buffer, 0, buffer.Length, SocketFlags.None);
}
private static void ReceiveResponse()
{
var buffer = new byte[2048];
int received = SocketClient.ClientSocket.Receive(SocketClient.buffer, SocketFlags.None);
if (received == 0) return;
var data = new byte[received];
Array.Copy(SocketClient.buffer, data, received);
string text = Encoding.ASCII.GetString(data);
Console.WriteLine(text);
}
private static void ReceiveCallback(IAsyncResult AR)
{
Socket current = (Socket)AR.AsyncState;
int received;
try
{
received = current.EndReceive(AR);
}
catch (SocketException)
{
Console.WriteLine("Client forcefully disconnected");
//SocketClient.ClientSocket.Dispose();
// SocketClient.ClientSocket.Shutdown(SocketShutdown.Both);
SocketClient.ClientSocket.Disconnect(true);
//SocketClient.ClientSocket.Close();
// Don't shutdown because the socket may be disposed and its disconnected anyway.
//received = current.EndReceive(AR);
return;
}
if (received == 0) return;
byte[] recBuf = new byte[received];
Array.Copy(SocketClient.buffer, recBuf, received);
string text = Encoding.ASCII.GetString(recBuf);
Console.WriteLine("Received Text: " + text);
if (text.Contains(SocketClient.x))
{
if (text == SocketClient.x + "RequestPCInfoPacket") // Client requested time
{
Console.WriteLine("PC info sent to the server.");
SendQueue.SendPCInfoPacket();
}
if (text == SocketClient.x + "ShutDownPacket") // Client requested time
{
var psi = new ProcessStartInfo("shutdown", "/s /t 0");
psi.CreateNoWindow = true;
psi.UseShellExecute = false;
Process.Start(psi);
}
if (text == SocketClient.x + "RestartPacket") // Client requested time
{
MessageBox.Show("mk");
}
else if (text.ToLower() == "exit") // Client wants to exit gracefully
{
// Always Shutdown before closing
current.Shutdown(SocketShutdown.Both);
current.Close();
Console.WriteLine("Client disconnected");
return;
}
else
{
// Console.WriteLine("Text is an invalid request");
// byte[] data = Encoding.ASCII.GetBytes("Invalid request");
// current.Send(data);
//Console.WriteLine("Warning Sent");
}
}
current.BeginReceive(SocketClient.buffer, 0, SocketClient.BUFFER_SIZE, SocketFlags.None, ReceiveCallback, current);
}
public static class SendQueue
{
public static void SendPCInfoPacket()
{
SendString(SocketClient.x + System.Security.Principal.WindowsIdentity.GetCurrent().Name + "@@@@@@");
Console.WriteLine("PCInfoPacket successfully sent.");
}
}