依造個人需求,在使用TCP設計客戶端(Client)時,有時候使用Socket方便;有時候使用TcpClient方便。所以今天我提供2種常使用與容易使用的方式,且不需要事先宣告byte[]來當作緩衝(Buffer),也不需要用迴圈把byte一個一個讀取出來。如此一來可以專心在商業邏輯上,加快程式的選寫速度與維護。

方法一 使用 Socket:

using System;
using System.Net;
using System.Net.Sockets;
using System.IO;

class Program
{
    static void Main(string[] args)
    {
        Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        socket.Connect("61.227.71.237", 1024); // 1.設定 IP:Port 2.連線至伺服器
        NetworkStream stream = new NetworkStream(socket);
        StreamReader sr = new StreamReader(stream);
        StreamWriter sw = new StreamWriter(stream);
        
        sw.WriteLine("你好伺服器,我是客戶端。"); // 將資料寫入緩衝
        sw.Flush(); // 刷新緩衝並將資料上傳到伺服器

        Console.WriteLine("從伺服器接收的資料: " + sr.ReadLine());
        
        Console.ReadLine();
    }
}

方法二 使用 TcpClient :

using System;
using System.Net;
using System.Net.Sockets;
using System.IO;

class Program
{
    static void Main(string[] args)
    {
        TcpClient tcp = new TcpClient("61.227.71.237", 1024); // 1.設定 IP:Port 2.連線至伺服器
        NetworkStream stream = new NetworkStream(tcp.Client);
        StreamReader sr = new StreamReader(stream);
        StreamWriter sw = new StreamWriter(stream);

        sw.WriteLine("你好伺服器,我是客戶端。"); // 將資料寫入緩衝
        sw.Flush(); // 刷新緩衝並將資料上傳到伺服器

        Console.WriteLine("從伺服器接收的資料: " + sr.ReadLine());

        Console.ReadLine();
    }
}

 

 

 

arrow
arrow
    全站熱搜

    黃彥霖 發表在 痞客邦 留言(0) 人氣()