C#。客户端服务器应用程序

时间:2020-07-12 13:37:06

标签: c# tcp

我制作了一个使用TCP协议的小型服务器应用程序。它已经能够在多个客户端之间建立连接。问题在于它在本地工作。所以我想知道如何获取主机的IP地址并使服务器接受Internet上的客户端连接?

public static class Server
{
    static Socket socket = new Socket(SocketType.Stream, ProtocolType.Tcp);
    static int nextID = 1;
    static List<Socket> clients = new List<Socket>(5);
    static MemoryStream stream = new MemoryStream(new byte[256], 0, 256, true, true);
    static BinaryReader reader = new BinaryReader(stream);
    static BinaryWriter writer = new BinaryWriter(stream);
    public static void Init()
    {
        Console.Title = "Server";
        socket.Bind(new IPEndPoint(IPAddress.Any, 8080));
        socket.Listen(0);
        socket.BeginAccept(AcceptCallBack, null);
        
        Console.ReadLine();
    }

    static void AcceptCallBack(IAsyncResult ar)
    {
        Socket client = socket.EndAccept(ar);
        clients.Add(client);
        Thread thread = new Thread(HandleClient);
        thread.Start(client);
        socket.BeginAccept(AcceptCallBack, null);
    }

    static void HandleClient(object obj)
    {
        Socket client = (Socket)obj;
        while(true)
        {
            stream.Position = 0;
            client.Receive(stream.GetBuffer());

            int code = reader.ReadInt32();

            switch(code)
            {
                case 0:
                    writer.Write(nextID++);
                    socket.Send(stream.GetBuffer());
                    break;
                case 1:
                    foreach (Socket cl in clients)
                        if (cl != client)
                            cl.Send(stream.GetBuffer());
                    break;
            }
        }
    }
}

0 个答案:

没有答案