客戶端完整程式碼 (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()); }
}
}
運作流程
- 啟動時連線
localhost:1234。
- 輸入文字按 Send,透過
StreamWriter 送出。
StreamReader.ReadLine() 同步等待伺服器回應。
- 將回應顯示於
ListBox。