.net之訪問Internet(下)

來源:互聯網
上載者:User

這裡介紹一下TCPClient類和Socket類,主要以兩個例子分析一下這兩個類在接收發送資料上的不同

TCP樣本:

TCP Sender, 發送資料到server端

using System;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.IO;

namespace TCPSender
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            TcpClient client = new TcpClient(textBox1.Text, Int32.Parse(textBox2.Text));//textBox1用來輸入地址,textBox2用來輸入訪問連接埠
            NetworkStream ns = client.GetStream();
            FileStream fs = File.Open("Form1.cs", FileMode.Open);

            int data = fs.ReadByte();
            while (data != -1)
            {
                ns.WriteByte((byte)data);
                data = fs.ReadByte();
            }

            fs.Close();
            ns.Close();
            client.Close();
        }
    }
}

 

TCP Receiver, 監聽並接收資料

using System;
using System.Windows.Forms;
using System.Threading;
using System.Net;
using System.Net.Sockets;
using System.IO;

namespace TCPReceiver
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            Thread thread = new Thread(new ThreadStart(Listen));
            thread.Start();
        }

        public void Listen()
        {
            IPAddress localAddr = IPAddress.Parse("127.0.0.1");
            Int32 port = 2112;
            TcpListener listener = new TcpListener(localAddr, port);
            listener.Start();

            TcpClient tcpClient = listener.AcceptTcpClient();
            NetworkStream ns = tcpClient.GetStream();
            StreamReader sr = new StreamReader(ns);
            string result = sr.ReadToEnd();
            Invoke(new UpdateDisplayDelegate(UpdateDisplay), new object[] { result });

            tcpClient.Close();
            listener.Stop();
        }

        public void UpdateDisplay(string text)
        {
            textBox1.Text = text;
        }

        protected delegate void UpdateDisplayDelegate(string text);
    }
}

最後執行結果如下:

 

Socket樣本

 Socket資訊發送端:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;

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

            //use the local host to create a IPEndPoint, which is connection end point
            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.");

            //to create a sender
            Socket sender = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            sender.Connect(ipEndPoint);

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

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

            //send messages
            sender.Send(forwardMessage);

            //receive the server response
            int totalBytesReceived = sender.Receive(receivedBytes);

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

            //shut down and dispose
            sender.Shutdown(SocketShutdown.Both);
            sender.Close();

            Console.ReadLine();
        }
    }
}

socket資訊監聽端:

using System.Text;
using System.Net.Sockets;
using System.Net;

namespace SockedListener
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Starting: Creating Socket object.");

            //The Socket class allows you to perform both synchronous and asynchronous data transfer using any of the communication protocols listed in the ProtocolType enumeration.
            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");

                //The Accept method processes any incoming connection requests and returns a Socket that you can use to communicate data with the remote host.
                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();
            }

            listener.Close();
        }
    }

執行結果:

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.