C# Socket模擬發(fā)送接收

Socket簡介

通過TCP/IP與儀器或設(shè)備通訊,在C#語言中,我們通常采用Socket。本項目是一個簡單的Socket建立服務(wù)監(jiān)聽與Socket作為客戶端請求的一個示例。

項目結(jié)構(gòu)

  • 客戶端項目 SocketClient

    主要負(fù)責(zé)作為Socket客戶端發(fā)起連接請求,并發(fā)送數(shù)據(jù)

  • 服務(wù)端項目 SocketDemo

    主要負(fù)責(zé)作為Socket服務(wù)端,監(jiān)聽端口并接收連接請求,并返回應(yīng)答數(shù)據(jù)

項目演示

  • 先運(yùn)行SocketDemo進(jìn)行服務(wù)監(jiān)聽
            Console.WriteLine("Starting:Creating Socket object");
            Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            listener.Bind(new IPEndPoint(IPAddress.Any, 2112));
            listener.Listen(10);

            while (true)
            {
                Console.WriteLine("Waiting for connection on port 2112");
                Socket socket = listener.Accept();
                string receivedValue = string.Empty;

                while (true)
                {
                    byte[] receivedBytes = new byte[1024];
                    int numBytes = socket.Receive(receivedBytes);
                    Console.WriteLine("Receiving.");
                    receivedValue += Encoding.ASCII.GetString(receivedBytes, 0, numBytes);
                    if (receivedValue.IndexOf("[FINAL]") > -1)
                    {
                        break;
                    }
                }

                Console.WriteLine("Received value:{0}", receivedValue);
                string replyValue = "Message successfully received.";
                byte[] replyMessage = Encoding.ASCII.GetBytes(replyValue);
                socket.Send(replyMessage);
                socket.Shutdown(SocketShutdown.Both);
                socket.Close();
            }
  • 運(yùn)行SocketClient進(jìn)行模擬連接,并發(fā)送接收數(shù)據(jù)。
            byte[] receivedBytes = new byte[1024];
            IPHostEntry ipHost = Dns.Resolve("127.0.0.1");
            IPAddress ipAddress = ipHost.AddressList[0];
            IPEndPoint ipEndPoint = new IPEndPoint(ipAddress, 2112);
            Console.WriteLine("Starting:Creating Socket object");

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

            sender.Connect(ipEndPoint);
            Console.WriteLine("Successfully connected to {0}", sender.RemoteEndPoint);

            string sendingMessage = "Hello World Socket Test";
            Console.WriteLine("Creating Message;Hello World Socket Test");

            byte[] forwardMessage = Encoding.ASCII.GetBytes(sendingMessage + "[FINAL]");


            sender.Send(forwardMessage);

            int totalBytesReceived = sender.Receive(receivedBytes);
            Console.WriteLine("Message provided from server: {0}", Encoding.ASCII.GetString(receivedBytes, 0, totalBytesReceived));

            sender.Shutdown(SocketShutdown.Both);
            sender.Close();
            Thread.Sleep(1000);

            Console.ReadLine();

后記

H5支持WebSocket,預(yù)計將來在通訊領(lǐng)域應(yīng)用會更加廣泛,示例程序見博客:[C# WebSocket模擬發(fā)送接收](http://www.cnblogs.com/bmbh/p/5174884.html)

GitHub

BMBH/.NET-Demo

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容