tcpclient與tcplistener

客戶端

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

namespace tcpclient
{
    class Program
    {
        static void Main(string[] args)
        {
            //當我們創建tcpclient對象的時候,就會跟server建立連接
            TcpClient client = new TcpClient("192.168.3.41",7788);

            NetworkStream stream = client.GetStream();//通過網絡流進行數據交換

            while (true)
            {
                string message = Console.ReadLine();
                byte[] data = Encoding.UTF8.GetBytes(message);
                stream.Write(data, 0, data.Length);
            }
                  
            stream.Close();
            client.Close();
            Console.ReadKey();

        }
    }
}

服務器端

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

namespace tcplistener
{
    class Program
    {
        static void Main(string[] args)
        {
            //TcpListener對Socket進行了一層封裝,這個類裏面自己會去創建socket對象
            TcpListener listener = new TcpListener(IPAddress.Parse("192.168.3.41"), 7788);

            //開始進行監聽
            listener.Start();

            //等待客戶端鏈接過來
            TcpClient client = listener.AcceptTcpClient();

            //取得客戶端發送過來的數據
            NetworkStream stream= client.GetStream(); //得到了網絡流,從這個網絡流可以取得客戶端發送過來的數據

            byte[] data = new byte[1024];


            while (true)
            {
                int length = stream.Read(data, 0, 1024);//讀取數據 1024表示最大讀取字節數
                string message = Encoding.UTF8.GetString(data, 0, length);
                Console.WriteLine("收到了消息:" + message);

            }
            
            stream.Close();
            client.Close();
            listener.Stop();

            Console.ReadKey();

        }
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章