Я пытаюсь создать локальный сервер winform, который принимает строку от клиента, а затем отправляет ответ клиенту на основе строки, которую отправляет клиент.
это мой код, так что мне удается получитьстрока «test» от клиента, но при возврате ответа я получаю сообщение об ошибке в функции AcceptCallback
, поведение, которое требует много времени для ответа, и когда я закрываю сервер, когда он отправляет сообщение «ok»,любое предложение было бы здорово.
ошибка {"Cannot access a disposed object.\r\nObject name: 'System.Net.Sockets.Socket'."}
namespace ServerSocket
{
public partial class Form1 : Form
{
private static Socket _clientSocket = new Socket
(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
private static Socket _serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
private static List<Socket> _clientSockets = new List<Socket>();
private static readonly int _BUFFER_SIZE = 2048;
private static byte[] _buffer = new byte[_BUFFER_SIZE];
string text;
Socket current;
Socket test;
delegate void SetTextCallback(string text);
public Form1()
{
InitializeComponent();
}
private void SetText(string text)
{
// InvokeRequired required compares the thread ID of the
// calling thread to the thread ID of the creating thread.
// If these threads are different, it returns true.
if (this.richTextBox1.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(SetText);
this.Invoke(d, new object[] { text });
}
else
{
this.richTextBox1.Items.Add(text);
}
}
private void Form1_Load(object sender, EventArgs e)
{
SetupServer();
}
private void SetupServer()
{
SetText("Setting up server...");
_serverSocket.Bind(new IPEndPoint(IPAddress.Any, 8999));
_serverSocket.Listen(5);
_serverSocket.BeginAccept(new AsyncCallback(AcceptCallback), null);
SetText("Server Setup");
}
private static void CloseAllSockets()
{
foreach (Socket socket in _clientSockets)
{
socket.Shutdown(SocketShutdown.Both);
socket.Close();
}
_serverSocket.Close();
}
private void AcceptCallback(IAsyncResult AR)
{
Socket socket = null;
try
{
socket = _serverSocket.EndAccept(AR); // problem is here
}
catch (ObjectDisposedException)
{
return;
}
_clientSockets.Add(socket);
socket.BeginReceive(_buffer, 0, _BUFFER_SIZE, SocketFlags.None, new AsyncCallback(ReceiveCallback), socket);
SetText("Client connected, waiting for request...");
test = (Socket)AR.AsyncState;
_serverSocket.BeginAccept(new AsyncCallback(AcceptCallback), null);
}
private void ReceiveCallback(IAsyncResult AR)
{
current = (Socket)AR.AsyncState;
int received = 0;
try
{
received = current.EndReceive(AR);
}
catch (SocketException)
{
SetText("Client forcefully disconnected");
current.Close(); // Dont shutdown because the socket may be disposed and its disconnected anyway
_clientSockets.Remove(current);
return;
}
byte[] recBuf = new byte[received];
Array.Copy(_buffer, recBuf, received);
text = Encoding.ASCII.GetString(recBuf);
SetText("Received Text: " + text);
if (text.ToLower() == "test") // Client requested time
{
SetText("Text is a get time request");
byte[] data = Encoding.ASCII.GetBytes("ok");// Encoding.ASCII.GetBytes(DateTime.Now.ToLongTimeString());
current.Send(data);
}
else
{
SetText("Server is sending invalid packet");
SetText("Warning Sent");
}
current.BeginReceive(_buffer, 0, _BUFFER_SIZE, SocketFlags.None, new AsyncCallback(ReceiveCallback), current);
}
private void Send_Received(string mess)
{
byte[] data = Encoding.ASCII.GetBytes(mess);
test.Send(data);
}
private void button1_Click(object sender, EventArgs e)
{
CloseAllSockets();
}
}