三国卡牌客户端基础资源仓库
yyl
2025-06-16 a0c0dbcda79206c552f6bb7deb80589d97d9ae70
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
 using System;
using System.Net;
using System.Threading;
 
namespace Microsoft.Unity.VisualStudio.Editor.Messaging
{
    internal class TcpListener
    {
        private const int ListenTimeoutMilliseconds = 5000;
 
        private class State
        {
            public System.Net.Sockets.TcpListener TcpListener;
            public byte[] Buffer;
        }
 
        public static int Queue(byte[] buffer)
        {
            var tcpListener = new System.Net.Sockets.TcpListener(IPAddress.Any, 0);
            var state = new State {Buffer = buffer, TcpListener = tcpListener};
 
            try
            {
                tcpListener.Start();
 
                int port = ((IPEndPoint)tcpListener.LocalEndpoint).Port;
 
                ThreadPool.QueueUserWorkItem(_ =>
                {
                    bool listening = true;
                    
                    while (listening)
                    {
                        var handle = tcpListener.BeginAcceptTcpClient(OnIncomingConnection, state);
                        listening = handle.AsyncWaitHandle.WaitOne(ListenTimeoutMilliseconds);
                    }
                    
                    Cleanup(state);
                });
 
                return port;
            }
            catch (Exception)
            {
                Cleanup(state);
                return -1;
            }
        }
 
        private static void OnIncomingConnection(IAsyncResult result)
        {
            var state = (State)result.AsyncState;
 
            try
            {
                using (var client = state.TcpListener.EndAcceptTcpClient(result))
                {
                    using (var stream = client.GetStream())
                    {
                        stream.Write(state.Buffer, 0, state.Buffer.Length);
                    }
                }
            }
            catch (Exception)
            {
                // Ignore and cleanup
            }
        }
 
        private static void Cleanup(State state)
        {
            state.TcpListener?.Stop();
 
            state.TcpListener = null;
            state.Buffer = null;
        }
    }
}