首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C# 網路程式設計初探(四):完整用戶端程式碼、執行畫面與總結

     編輯:關於C語言

用戶端特點:無需監聽、無阻塞、無執行緒

用戶端不需監聽網路,呼叫無阻塞,故不需額外執行緒,與伺服器端不同。

完整用戶端程式碼:Client.cs

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Net.Sockets;
using System.IO;
using System.Threading;

public class Form1 : Form
{
    private ListBox ListBox1;
    private Label label1, label2;
    private TextBox textBox1;
    private Button button3;
    private NetworkStream networkStream;
    private StreamReader streamReader;
    private StreamWriter streamWriter;
    private TcpClient myClient;
    private Container components = null;

    public Form1() { InitializeComponent(); }

    protected override void Dispose(bool disposing)
    {
        if (disposing && components != null) components.Dispose();
        base.Dispose(disposing);
    }

    private void InitializeComponent()
    {
        label1 = new Label(); button3 = new Button();
        ListBox1 = new ListBox(); textBox1 = new TextBox(); label2 = new Label();
        SuspendLayout();
        label1.Location = new Point(8, 168); label1.Name = "label1";
        label1.Size = new Size(56, 23); label1.TabIndex = 3; label1.Text = "訊息:";
        AutoScaleBaseSize = new Size(6, 14);
        ClientSize = new Size(424, 205);
        Controls.Add(button3); Controls.Add(textBox1); Controls.Add(label1);
        Controls.Add(label2); Controls.Add(ListBox1);
        MaximizeBox = false; MinimizeBox = false;
        Name = "Form1"; Text = "C# 網路程式用戶端!";
        Closed += new EventHandler(Form1_Closed);
        ResumeLayout(false);

        try
        {
            myClient = new TcpClient("localhost", 1234);
        }
        catch { MessageBox.Show("無法連接伺服器!"); return; }

        networkStream = myClient.GetStream();
        streamReader = new StreamReader(networkStream);
        streamWriter = new StreamWriter(networkStream);
    }

    static void Main() { Application.Run(new Form1()); }

    private void button3_Click(object sender, EventArgs e)
    {
        if (textBox1.Text == "") { MessageBox.Show("請輸入訊息!"); textBox1.Focus(); return; }
        try
        {
            streamWriter.WriteLine(textBox1.Text);
            streamWriter.Flush();
            string s = streamReader.ReadLine();
            ListBox1.Items.Add("讀取伺服器回應:" + s);
        }
        catch (Exception ex) { MessageBox.Show("讀取錯誤:" + ex.ToString()); }
    }

    private void Form1_Closed(object sender, EventArgs e)
    {
        streamReader.Close(); streamWriter.Close(); networkStream.Close();
    }
}

執行畫面

圖01:C# 網路程式執行介面

總結

.NET Framework 僅以 System.Net、System.Net.Sockets 兩命名空間封裝豐富網路功能,支援同步/非同步、阻塞/非阻塞。本文以資料傳輸程式展示基礎用法,進階功能留待讀者探索。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved