简体   繁体   English

CSharp异步服务器程序在启动时立即关闭

[英]CSharp async server program immediately closes at start

im pretty to new to programming and i've just now wrote my first async server, but as soon as i start the program, it closes right after writing waiting for new client, can someone help me out? 我对编程很陌生,我刚刚编写了我的第一个异步服务器,但是一旦启动程序,它在编写等待新客户端后立即关闭,有人可以帮帮我吗? I dont know what stupid thing im doing. 我不知道什么愚蠢的事情即时通讯做。 I have a class UDPServer with some methods, of which - UDPServer() receives an ipendpoint of the localserver ipaddress and port to initialize stuff (called in main to create a new UDP server object) - right after that i call the get connection method, which supposedly should make the server wait for a new client, but instead it immediately closes. 我有一个带有某些方法的UDPServer类,其中-UDPServer()接收本地服务器ipaddress和端口的ipendpoint来初始化内容(在main中调用以创建新的UDP服务器对象)-之后,我调用get连接方法,据说这应该使服务器等待新的客户端,但是它立即关闭。

// State object for reading client data asynchronously  
public class StateObject
{
    // Client  socket.  
    public Socket clientSocket = null;
    // Size of receive buffer.  
    public const int BufferSize = 1024;
    // Receive buffer.  
    public byte[] buffer = new byte[BufferSize];
    // Received data string.  
    public StringBuilder sb = new StringBuilder();
}


class UDPServer
{
    Socket serverSocket;
    IPEndPoint localIPEP;
    IPEndPoint senderIPEP;
    EndPoint sender;

    IPEndPoint[,] playerList; 
    int playerListIndex;

    bool waitingForSecondClient;

    public UDPServer(IPEndPoint serverIpEndPoint)
    {
        localIPEP = serverIpEndPoint;
        serverSocket = new Socket(AddressFamily.InterNetwork,SocketType.Dgram,ProtocolType.Udp);

        serverSocket.Bind(localIPEP);

        senderIPEP = new IPEndPoint(IPAddress.Any, 0);
        sender = senderIPEP;

        playerList = new IPEndPoint[5000, 2]; // 5000 possible player lobbies, each with 2 player ip addresses and ports
        playerListIndex = 0; // we start filling up the lobbies from 0
        Console.WriteLine("Server setup complete.");
    }

    public void GetConnection()
    {
        StateObject state = new StateObject();
        Console.WriteLine("Waiting for new client.");
        serverSocket.BeginReceiveFrom(state.buffer, 0, StateObject.BufferSize, SocketFlags.None,ref sender, ClientConnected, state);
    }

    public void ClientConnected(IAsyncResult asyncResult)
    {
        StateObject state = (StateObject)asyncResult;
        EndPoint remote = state.clientSocket.LocalEndPoint;
        StateObject tempState = new StateObject();
        int bytesReceived = serverSocket.EndReceiveFrom(asyncResult, ref remote);
        serverSocket.BeginReceiveFrom(tempState.buffer, 0, StateObject.BufferSize, SocketFlags.None, ref remote, ClientConnected, tempState);


        Console.WriteLine("-------------");
        Console.WriteLine("Received bytes of data: " + bytesReceived);
        Console.WriteLine("-------------");
        Console.WriteLine("Received string: " + state.sb.ToString());
        Console.WriteLine("-------------");

        if (state.sb.ToString().Equals("New client"))
        {
            Send(state.clientSocket, "Hello");
        }
    }

    private void Send(Socket client,string message)
    {
        EndPoint remote = client.LocalEndPoint;

        StateObject state = new StateObject();

        // Begin sending the data to the remote device.  
        serverSocket.BeginSendTo(state.buffer, 0, StateObject.BufferSize, 0,remote,SendCallback,state);
    }

    private static void SendCallback(IAsyncResult asyncResult)
    {
        // Retrieve the socket from the state object.  
        Socket client = (Socket)asyncResult.AsyncState;

        // Complete sending the data to the remote device.  
        int bytesSent = client.EndSendTo(asyncResult);
    }

    static void Main(string[] args)
    {
        UDPServer server = new UDPServer(new IPEndPoint(IPAddress.Any, 9050));
        server.GetConnection();
    }
}

BeginReceiveFrom Does not block, as such program execution reaches the end of your main method and finishes. BeginReceiveFrom不会阻塞,因为这样的程序执行会到达您的main方法的末尾并完成。 I am not sure what you intend your exit condition to be, but you will need some sort of code making sure the server waits until that exit condition is met before finishing program execution. 我不确定您希望退出条件是什么,但是您将需要某种代码来确保服务器在完成程序执行之前一直等到满足退出条件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM