C#程式設計和網路程式設計
阿新 • • 發佈:2020-11-04
一、C#簡單helloworld程式
1.用C#編寫一個命令列/控制檯hello world程式,實現如下功能:在螢幕上連續輸出50行“hello cqjtu!重交物聯2018級”;
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace helloworld控制檯 { class Program { static void Main(string[] args) { for (int i = 0; i < 50; i++) { Console.WriteLine("hello cqjtu!重交物聯2018級"); } Console.ReadKey(); } } }
2.建立一個server伺服器和client進行通訊程式設計
伺服器程式碼
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Net.Sockets; using System.Net; namespace server { class Program { static void Main(string[] args) { UdpClient udpRec = new UdpClient(8888); Console.WriteLine("伺服器已開啟!"); try { while (true) { IPEndPoint remoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0); byte[] recBytes = udpRec.Receive(ref remoteIpEndPoint); string returnData = Encoding.Default.GetString(recBytes); Console.WriteLine("接收到的資料是:" + returnData); } } catch (Exception e) { Console.WriteLine(e); } finally { udpRec.Close(); } } } }
客戶端程式碼:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Net.Sockets; using System.Net; namespace client { class Program { static void Main(string[] args) { int j = 0; while (j < 50) { Console.WriteLine("hello cqjtu!重交物聯2018級"); j++; } UdpClient client = new UdpClient("127.0.0.1", 8888); Console.WriteLine("正在準備傳送資料!"); try { while (j>0) { string str = "hello cqjtu!重交物聯2018級"; byte[] sendBytes = Encoding.Default.GetBytes(str); client.Send(sendBytes, sendBytes.Length); j--; } } catch (Exception e) { Console.WriteLine(e); } finally { client.Close(); } Console.WriteLine("資料傳送成功!"); Console.Read(); } } }
二、寫一個Form視窗程式
用VS2015/2017 的C#編寫一個簡單的Form視窗程式,有一個文字框 textEdit和一個傳送按鈕button,執行程式後,可以在文字框裡輸入文字,如“hello cqjtu物聯18!”,點選button,將這些文字傳送給室友電腦或樹莓派,採用UDP套接字;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace Server
{
public partial class Form1 : Form
{
private UdpClient receiveUdpClient;//接收用
private UdpClient sendUdpClient;//傳送用
private const int port = 8888;//和本機繫結的埠號
IPAddress ip;//本機ip
IPAddress remoteip;//=IPAddress.Parse("");遠端主機ip
public Form1()
{
InitializeComponent();
CheckForIllegalCrossThreadCalls = false;
//獲取本機可用IP地址
IPAddress[] ips = Dns.GetHostAddresses(Dns.GetHostName());
foreach (IPAddress ipa in ips)
{
if (ipa.AddressFamily == AddressFamily.InterNetwork)
{
ip = ipa;
break;
}
}
//為了在同一臺機器除錯,此IP也作為預設遠端IP
remoteip = ip;
}
private void Form1_Load(object sender, EventArgs e)
{
//建立一個執行緒接收遠端主機發來的資訊
Thread myThread = new Thread(ReceiveData);
myThread.IsBackground = true;
myThread.Start();
}
//接收資料
private void ReceiveData()
{
IPEndPoint local = new IPEndPoint(ip, port);
receiveUdpClient = new UdpClient(local);
IPEndPoint remote = new IPEndPoint(IPAddress.Any, 0);
while (true)
{
try
{
//關閉udpClient 時此句會產生異常
byte[] receiveBytes = receiveUdpClient.Receive(ref remote);
string receiveMessage = Encoding.Unicode.GetString(
receiveBytes, 0, receiveBytes.Length);
listBox1.Items.Add("收到的訊息:" + receiveMessage);
}
catch
{
break;
}
}
}
//點擊發送按鈕傳送資料
private void button1_Click(object sender, EventArgs e)
{
//remoteip = IPAddress.Parse(txt_IPAddress.Text);
Thread myThread = new Thread(SendMessage);
myThread.IsBackground = true;
myThread.Start(textBox2.Text);
}
//傳送訊息
private void SendMessage(object obj)
{
string message = (string)obj;
sendUdpClient = new UdpClient(0);
byte[] bytes = Encoding.Unicode.GetBytes(message);
IPEndPoint iep = new IPEndPoint(remoteip, port);
try
{
sendUdpClient.Send(bytes, bytes.Length, iep);
listBox1.Items.Add("傳送的訊息:" + message);
textBox2.Clear();
}
catch (Exception ex)
{
listBox1.Items.Add("傳送出錯:" + ex.Message);
}
}
delegate void AddItemDelegate(ListBox listbox, string text);
private void AddItem(ListBox listbox, string text)
{
if (listbox.InvokeRequired)
{
AddItemDelegate d = AddItem;
//Control.Invoke 方法 (Delegate, Object[]):
//在擁有控制元件的基礎視窗控制代碼的執行緒上,用指定的引數列表執行指定委託。
listbox.Invoke(d, new object[] { listbox, text });
}
else
{
//Add:動態的新增列表框中的項
listbox.Items.Add(text);
//SelectedIndex屬性獲取單項選擇ListBox中當前選定項的位置
//Count:列表框中條目的總數
listbox.SelectedIndex = listbox.Items.Count - 1;
//呼叫此方法等效於將 SelectedIndex 屬性設定為-1。
//可以使用此方法快速取消選擇列表中的所有項。
listbox.ClearSelected();
}
}
delegate void ClearTextBoxDelegate();
private void ClearTextBox()
{
if (textBox2.InvokeRequired)
{
ClearTextBoxDelegate d = ClearTextBox;
textBox2.Invoke(d);
}
else
{
textBox2.Clear();
textBox2.Focus();
}
}
private void label2_Click(object sender, EventArgs e)
{
}
private void label2_Click_1(object sender, EventArgs e)
{
}
}
}
三、wirshark
安裝wireshark 抓包軟體,抓取上述程式傳送的網路包,對資料幀結構進行分析
前四行分別為源埠,目的埠,長度,校驗和。
每一個各佔2byte,一共8byte。
傳送的訊息為:“你好,重慶交通大學”,一共9個字元,18byte,18+8=26,即長度。