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