비동기 소켓통신 구문오류에 대한 질문입니다.

아래 소스인데요… 유튜브에선 이 소스가 잘돌아 갑니다.
확인해본 결과 아무 문제 없는데요 이부분을 빼면
BeginReceive(…, ReceiveCallback, ,… , _cli_socket);
부분으로 해서 ReceiveCallabck 부분 처리하는 데에
Socket current = (Socket)AR.AsyncState; 이부분이 밑줄이 계속 가더라고요
오류 :
null 리터럴 또는 가능한 null 값을 null을 허용하지 않는 형식으로 변환하는 중입니다.

using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;

namespace MultiServer
{

    class Program

    {

        private static readonly Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

        private static readonly List<Socket> clientSockets = new List<Socket>();

        private const int BUFFER_SIZE = 2048;

        private const int PORT = 100;

        private static readonly byte[] buffer = new byte[BUFFER_SIZE];

        static void Main()

        {

            Console.Title = "Server";

            SetupServer();

            Console.ReadLine(); // When we press enter close everything

            CloseAllSockets();

        }

        private static void SetupServer()

        {

            Console.WriteLine("Setting up server...");

            serverSocket.Bind(new IPEndPoint(IPAddress.Any, PORT));

            serverSocket.Listen(0);

            serverSocket.BeginAccept(AcceptCallback, null);

            Console.WriteLine("Server setup complete");

        }

        /// <summary>

        /// Close all connected client (we do not need to shutdown the server socket as its connections

        /// are already closed with the clients).

        /// </summary>

        private static void CloseAllSockets()

        {

            foreach (Socket socket in clientSockets)

            {

                socket.Shutdown(SocketShutdown.Both);

                socket.Close();

            }

            serverSocket.Close();

        }

        private static void AcceptCallback(IAsyncResult AR)

        {

            Socket socket;

            try

            {

                socket = serverSocket.EndAccept(AR);

            }

            catch (ObjectDisposedException) // I cannot seem to avoid this (on exit when properly closing sockets)

            {

                return;

            }

           clientSockets.Add(socket);

           socket.BeginReceive(buffer, 0, BUFFER_SIZE, SocketFlags.None, ReceiveCallback, socket);

           Console.WriteLine("Client connected, waiting for request...");

           serverSocket.BeginAccept(AcceptCallback, null);

        }

        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");

                // Don't shutdown because the socket may be disposed and its disconnected anyway.

                current.Close();

                clientSockets.Remove(current);

                return;

            }

            byte[] recBuf = new byte[received];

            Array.Copy(buffer, recBuf, received);

            string text = Encoding.ASCII.GetString(recBuf);

            Console.WriteLine("Received Text: " + text);

            if (text.ToLower() == "get time") // Client requested time

            {

                Console.WriteLine("Text is a get time request");

                byte[] data = Encoding.ASCII.GetBytes(DateTime.Now.ToLongTimeString());

                current.Send(data);

                Console.WriteLine("Time sent to client");

            }

            else if (text.ToLower() == "exit") // Client wants to exit gracefully

            {

                // Always Shutdown before closing

                current.Shutdown(SocketShutdown.Both);

                current.Close();

                clientSockets.Remove(current);

                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(buffer, 0, BUFFER_SIZE, SocketFlags.None, ReceiveCallback, current);
        }
    }
}
1 Like

질문글 올리실 때 올리기 전, 안내문구가 다 지워졌는지 점검 한 번 부탁드립니다.
또한 Markdown 문법 또한 지켜주시면 가독성이 더욱 좋아질 것 같습니다.

1 Like

컴파일 규칙을 설정하신 것 같은데 IAsyncResult.AsyncStateobject?로 nullable이네요.

임시로 비활성화하려면 커서를 올렸을 때 나오는 드롭박스 옵션에서 {규칙이름} 비활성화 비슷한 것 누르시면 됩니다.

아니면

Socket current = AR.AsyncState as Socket;

으로 시도해보시겠어요?

1 Like