1. 程式人生 > >C# 中使用Socket通訊

C# 中使用Socket通訊

伺服器

 class Program
    {
        static void Main(string[] args)
        {
            Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            serverSocket.Bind(new IPEndPoint(IPAddress.Parse("10.6.0.38"), 88));

            serverSocket.Listen(19
); serverSocket.BeginAccept(ClientAccept, serverSocket); Console.ReadLine(); } static byte[] buffer = new byte[1024]; static void ClientAccept(IAsyncResult ar) { Socket serverSocket = ar.AsyncState as Socket; Socket clientSocket = serverSocket.EndAccept
(ar); clientSocket.Send(Encoding.UTF8.GetBytes("hellooo")); clientSocket.BeginReceive(buffer, 0, 1024, SocketFlags.None, ServerReceive, clientSocket); serverSocket.BeginAccept(ClientAccept, serverSocket); } static void ServerReceive(IAsyncResult ar) { Socket clientSOcket = ar.AsyncState
as Socket; try { int len = clientSOcket.EndReceive(ar); if(len == 0) { clientSOcket.Close(); return; } Console.WriteLine(Encoding.UTF8.GetString(buffer, 0, len)); clientSOcket.BeginReceive(buffer, 0, 1024, SocketFlags.None, ServerReceive, clientSOcket); } catch (Exception e) { Console.WriteLine(e); clientSOcket.Close(); } Console.ReadLine(); } }

客戶端

class Program
    {
        static void Main(string[] args)
        {
            byte[] buffer = new byte[1024];

            Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            clientSocket.Connect(new IPEndPoint(IPAddress.Parse("10.6.0.38"), 88));

            int len = clientSocket.Receive(buffer, 0, 1024, SocketFlags.None);

            Console.WriteLine(Encoding.UTF8.GetString(buffer, 0, len));

            while (true)
            {
                string temp = Console.ReadLine();

                if (temp == "c")
                {
                    clientSocket.Close();
                    return;
                }

                byte[] tempByte = Encoding.UTF8.GetBytes(temp);

                clientSocket.Send(tempByte);
            }

        }
    }