.net之访问Internet(下)

来源:互联网 发布:淘宝怎么发布二手闲置 编辑:程序博客网 时间:2024/06/08 19:34

这里介绍一下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();
        }
    }

执行结果:

原创粉丝点击