Answer the question
In order to leave comments, you need to log in
Reconnecting to a server on asynchronous C# sockets?
There is a server implemented through asynchronous sockets.
I only work with 1 client. Connection, reception and transmission work successfully.
The task is a little easier, before disconnecting the client sends the string "DISCONNECT".
Question: how to reconnect? For example, the client disconnects and reconnects after a while.
<br>
class Ethernet<br>
{<br>
public static byte[] buffer = new byte[1024];<br>
public static ManualResetEvent socketEvent = new ManualResetEvent(true);<br>
public static Socket handlerA;<br>
public static IPAddress ipAddr;<br>
public static IPEndPoint localEnd;<br>
<br>
public static void Start()<br>
{<br>
ipAddr = IPAddress.Parse("192.168.0.222");<br>
localEnd = new IPEndPoint(ipAddr, 1100);<br>
Socket sListener = new Socket(AddressFamily.InterNetwork,<br>
SocketType.Stream, ProtocolType.Tcp);<br>
sListener.Bind(localEnd);<br>
sListener.Listen(10);<br>
AsyncCallback aCallback = new AsyncCallback(AcceptCallback);<br>
sListener.BeginAccept(aCallback, sListener);<br>
socketEvent.WaitOne();<br>
}<br>
<br>
public static void AcceptCallback(IAsyncResult ar)<br>
{<br>
Socket listner = (Socket)ar.AsyncState;<br>
Socket handler = listner.EndAccept(ar);<br>
handlerA = handler;<br>
handler.BeginReceive(buffer, 0, buffer.Length, 0,<br>
new AsyncCallback(ReceiveCallback), handler);<br>
}<br>
<br>
public static void ReceiveCallback(IAsyncResult ar)<br>
{<br>
string content = String.Empty;<br>
Socket handler = (Socket)ar.AsyncState;<br>
<br>
int bytesRead = handler.EndReceive(ar);<br>
<br>
if (bytesRead > 0)<br>
{<br>
content = Encoding.ASCII.GetString(buffer, 0, bytesRead);<br>
}<br>
<br>
if (content.ToUpper() != "DISCONNECT")<br>
{<br>
// Работа с пришедшей строкой<br>
handler.BeginReceive(buffer, 0, buffer.Length, 0,<br>
new AsyncCallback(ReceiveCallback), handler);<br>
}<br>
else<br>
{<br>
// Отключение<br>
}<br>
}<br>
<br>
public static void Send(string str)<br>
{<br>
byte[] byteData = Encoding.ASCII.GetBytes(str);<br>
handlerA.BeginSend(byteData, 0, byteData.Length, 0,<br>
new AsyncCallback(SendCallback), handlerA);<br>
}<br>
<br>
public static void SendCallback(IAsyncResult ar)<br>
{<br>
Socket handler = (Socket)ar.AsyncState;<br>
int bytesSend = handler.EndSend(ar);<br>
}<br>
}<br>
Answer the question
In order to leave comments, you need to log in
If the client is guaranteed 1 then there is no point in using asynchronous sockets.
In general, you just need to add:
sListener.BeginAccept(AcceptCallback, listener);
to the end of the function:
public static void AcceptCallback(IAsyncResult ar)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question