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

簡單 C# Socket 程式設計(二):客戶端實作與介面互動

     編輯:關於C語言

客戶端完整程式碼 (WinForms)

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

namespace SocketSample
{
    public class Sample : Form
    {
        Button btS; TextBox t1; ListBox t2;
        NetworkStream ns; StreamReader sr; StreamWriter sw;
        ArrayList sb = new ArrayList(); TcpClient client; bool flag = false;

        public Sample()
        {
            InitializeComponent();
            if (!flag) Connect();
            ns = client.GetStream();
            sr = new StreamReader(ns);
            sw = new StreamWriter(ns);
            ShowMessage();
        }

        void Connect()
        {
            try { sb.Add("Connecting..."); client = new TcpClient("localhost", 1234); sb.Add("Connected. Enter text."); }
            catch { sb.Add("Failed to connect to localhost:1234"); }
            flag = true;
        }

        void ShowMessage()
        {
            for (int i = 0; i < sb.Count; i++) t2.Items.Add(sb[i].ToString());
            sb.Clear();
        }

        void btS_Click(object sender, EventArgs e)
        {
            if (t1.Text == "") { sb.Add("Please enter text."); t1.Focus(); return; }
            try
            {
                sw.WriteLine(t1.Text); sw.Flush();
                string s = sr.ReadLine();
                sb.Add(s); t1.Text = ""; t1.Focus(); ShowMessage();
            }
            catch { MessageBox.Show("Error."); }
        }

        void t1_TextChanged(object sender, EventArgs e) => btS.Enabled = t1.Text != "";

        // InitializeComponent 略(含 btS, t1, t2 佈局)
        public static void Main() { Application.Run(new Sample()); }
    }
}

運作流程

  1. 啟動時連線 localhost:1234。
  2. 輸入文字按 Send,透過 StreamWriter 送出。
  3. StreamReader.ReadLine() 同步等待伺服器回應。
  4. 將回應顯示於 ListBox。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved