Tcp与Ip协议的客户端和服务器编程
生活随笔
收集整理的這篇文章主要介紹了
Tcp与Ip协议的客户端和服务器编程
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Tcp與Ip協議的客戶端和服務器編程
本文就TCP和Ip協議的客戶端和服務器分別進行編程,實現了客戶端和服務端進行通信的功能,服務端對多個客戶端進行監聽,并能與多個客戶端通信。
服務器端代碼如下:
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.IO; using System.Linq; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms;namespace 服務端 {public partial class Form1 : Form{public Form1(){InitializeComponent();}private void Form1_Load(object sender, EventArgs e){Control.CheckForIllegalCrossThreadCalls = false;}/// <summary>/// 獲取本機IP地址/// </summary>/// <returns>返回一個IP</returns>private string GetIpAddress(){string hostName = Dns.GetHostName();//獲取本機名IPHostEntry localhost = Dns.GetHostByName(hostName);//方法已過期了,只能得到一個IPV4的地址 IPAddress localaddr = localhost.AddressList[0];return localaddr.ToString();}private void btnStart_Click(object sender, EventArgs e){try{//當點擊開始監聽時,在服務器端創建一個負責監聽IP地址和端口號的Socket//IP V4,流式服務,TCP協議Socket socketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);IPAddress ip = IPAddress.Any; //IPAddress.Parse(txtServer.Text);我的理解是獲取本機IPtxtServer.Text = GetIpAddress();//將IP地址給文本//創建端口號對象IPEndPoint point = new IPEndPoint(ip, Convert.ToInt32(txtPort.Text));//監聽 socketWatch.Bind(point);ShowMsg("監聽成功");socketWatch.Listen(10);//一次監聽10 人///創建一個線程來監聽,否則沒監聽時就卡死了Thread th = new Thread(Listen);th.IsBackground = true;th.Start(socketWatch);}catch { }}Dictionary<string, Socket> dicSock = new Dictionary<string, Socket>();//創建鍵值對來存放IP和socket Socket socketSend;void Listen(object o)//必須用object類型 ,因為線程要使用 {Socket socketWatch = o as Socket;//將傳遞過來的參數轉換為Socket類型while (true){try{//等待客戶端的連接 并且創建一個負責通信的SocketsocketSend = socketWatch.Accept();//獲得遠端 IP+端口號:連接成功ShowMsg(socketSend.RemoteEndPoint.ToString() + ":" + "連接成功");dicSock.Add(socketSend.RemoteEndPoint.ToString(), socketSend);//將IP地址添加到下拉列表中 comboBox1.Items.Add(socketSend.RemoteEndPoint.ToString());Thread th = new Thread(ReciveMsg);//在線程中只寫方法名,括號和里面的參數不寫在這里th.IsBackground = true;//寫為后臺線程,這樣關閉窗口時線程就關閉了,否則關閉不了,會報錯 th.Start(socketSend);}catch{ }}}/// <summary>/// 用來接收客戶端發送來的信息,線程來調用他/// </summary>/// <param name="o"></param>void ReciveMsg(object o){Socket socketSend = o as Socket;while (true){try{//連接成功之后,客戶端就要給服務端發送數據了byte[] buffer = new byte[1024 * 1024 * 2];int r = socketSend.Receive(buffer);//實際接收到的有效字符if (r == 0){break;}string str = Encoding.UTF8.GetString(buffer, 0, r);ShowMsg(socketSend.RemoteEndPoint + ":" + str);}catch { }}}/// <summary>/// 在上面一個文本框中顯示信息的方法/// </summary>/// <param name="str"></param>void ShowMsg(string str){txtLOg.AppendText(str + "\r\n");//寫AppendText追加,不然會覆蓋 }/// <summary>/// 服務端給客戶端發送消息/// </summary>/// <param name="sender"></param>/// <param name="e"></param>private void button4_Click(object sender, EventArgs e){try{if (comboBox1.Text == ""){MessageBox.Show("請選中一個客戶端地址再發送消息", "謝謝");}string str = textBox4.Text;textBox4.Clear();byte[] buffer = System.Text.Encoding.UTF8.GetBytes(str);List<byte> list = new List<byte>();list.Add(0);list.AddRange(buffer);byte[] newbuffer = list.ToArray();string ip = comboBox1.SelectedItem.ToString();dicSock[ip].Send(newbuffer);//通過鍵IP地址找到值socketSend //socketSend.Send(buffer); }catch{ }}private void button2_Click(object sender, EventArgs e){if (comboBox1.Text == ""){MessageBox.Show("請選擇一個客戶端IP地址再選擇要發送的文件", "提示!");}else{OpenFileDialog ofd = new OpenFileDialog();ofd.Title = "請選擇要發送的文件";ofd.InitialDirectory = @"C:\Users\Administrator\Desktop";ofd.Filter = "所有文件|*.*";ofd.ShowDialog();textBox5.Text = ofd.FileName;//獲得選中的一個文件名 }}/// <summary>/// 發送文件/// </summary>/// <param name="sender"></param>/// <param name="e"></param>private void button3_Click(object sender, EventArgs e){try{//發送文件string path = textBox5.Text;using (FileStream fsRead = new FileStream(path, FileMode.Open, FileAccess.Read)){byte[] buffer = new byte[1024 * 1024 * 5];int r = fsRead.Read(buffer, 0, buffer.Length);List<byte> list = new List<byte>();list.Add(1);list.AddRange(buffer);byte[] newbuffer = list.ToArray();//int r= fsRead.Read(newbuffer , 0, newbuffer.Length);//實際讀取的有效字節dicSock[comboBox1.SelectedItem.ToString()].Send(newbuffer, 0, r + 1, SocketFlags.None);}}catch { }}///讓客戶端震動private void button5_Click(object sender, EventArgs e){try{if (comboBox1.Text == ""){MessageBox.Show("請選擇一個客戶端IP地址再震動", "提示!");}else{byte[] buffer = new byte[1];buffer[0] = 2;dicSock[comboBox1.SelectedItem.ToString()].Send(buffer);}}catch { }}} }?
客戶端代碼如下:
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.IO; using System.Linq; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms;namespace 客戶端 {public partial class Form1 : Form{public Form1(){InitializeComponent();}Socket socketConnect = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);private void button1_Click(object sender, EventArgs e){try{//建立負責通訊的Socketif (textBox1.Text == "" || textBox2.Text == ""){MessageBox.Show("IP地址或者端口號不能為空", "去你大爺的!");}IPAddress ip = IPAddress.Parse(textBox1.Text);IPEndPoint point = new IPEndPoint(ip, Convert.ToInt32(textBox2.Text));socketConnect.Connect(point);ShowMsg("連接成功");Thread th = new Thread(Receive);th.IsBackground = true;th.Start();}catch { }}void ShowMsg(string str){textBox3.AppendText(str + "\r\n");}private void button2_Click(object sender, EventArgs e){try{//客戶端要給服務器發送消息string str = textBox4.Text.Trim();//Trim()就是把所寫內容前后空格去除byte[] buffer = Encoding.UTF8.GetBytes(str);//System.Text.Encoding.UTF8.GetBytes(str); socketConnect.Send(buffer);textBox4.Clear();}catch { }}///寫一個不斷接收服務端發過來的消息的方法,創建線程來調用他void Receive(){try{while (true)//不停的接收 {byte[] buffer = new byte[1024 * 1024 * 3];int r = socketConnect.Receive(buffer);//實際接收到的有效字節數if (r == 0){break;}if (buffer[0] == 0)//接收到文字 {string str = Encoding.UTF8.GetString(buffer, 1, r - 1);ShowMsg(socketConnect.RemoteEndPoint + ":" + str);}else if (buffer[0] == 1){//接收的是文件SaveFileDialog ofd = new SaveFileDialog();//保存對話框 ofd.Title = "請選擇保存文件的路徑";ofd.InitialDirectory = @"C:\Users\Administrator\Desktop";ofd.Filter = "所有文件|*.*";ofd.ShowDialog(this);string path = ofd.FileName;using (FileStream fsWrite = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write)){fsWrite.Write(buffer, 1, r - 1);}MessageBox.Show("保存成功", "kao");}else if(buffer [0]==2){ZD();}}}catch { }} /// <summary> /// 寫個方法來使窗體震動 /// </summary>void ZD(){for (int i = 0; i < 500; i++){this.Location = new Point(200 , 200);this.Location = new Point(280 , 280);}}private void Form1_Load(object sender, EventArgs e){Control.CheckForIllegalCrossThreadCalls = false;}} }?
轉載于:https://www.cnblogs.com/xiaoyaohan/p/9755748.html
總結
以上是生活随笔為你收集整理的Tcp与Ip协议的客户端和服务器编程的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 晚上梦到猴子是怎么回事
- 下一篇: 做梦梦到香瓜是什么意思