日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 人文社科 > 生活经验 >内容正文

生活经验

C#_Socket网络编程实现的简单局域网内即时聊天,发送文件,抖动窗口。

發布時間:2023/11/27 生活经验 25 豆豆
生活随笔 收集整理的這篇文章主要介紹了 C#_Socket网络编程实现的简单局域网内即时聊天,发送文件,抖动窗口。 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
C#_Socket網絡編程實現的簡單局域網內即時聊天,發送文件,抖動窗口。

最近接觸了C#Socket網絡編程,試著做了試試(*^__^*)

實現多個客戶端和服務端互相發送消息

發送文件
抖動窗口功能  

服務端:

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 kehuduan
{public partial class Form1 : Form{public Form1(){InitializeComponent();}Dictionary<string,Socket> dicsocket = new Dictionary<string, Socket>();//鍵值集合,通過鍵能找到值private void button1_Click(object sender, EventArgs e){try{//創建監聽的socketSocket socketwatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//獲得ip地址IPAddress ip = IPAddress.Any;//Parse(textBox1.Text);//創建端口號對象IPEndPoint point = new IPEndPoint(ip, Convert.ToInt32(textBox2.Text));socketwatch.Bind(point);showmsg(DateTime.Now.ToString() + "監聽成功");//192.168.1.103:監聽成功socketwatch.Listen(10);//開始監聽。監聽隊列10人//開啟新線程解決卡頓Thread lis = new Thread(Listen);lis.IsBackground = true;lis.Start(socketwatch);}catch{}}Socket socketsend;/// <summary>/// 循環等待接入的客戶端/// </summary>/// <param name="o"></param>void Listen(object o){try{Socket socketwatch = o as Socket;while (true){//負責跟客戶端通信的Socketsocketsend = socketwatch.Accept();//把連進來的socket存到建值集合和下拉菜單中,實現給指定的客戶端發消息
                    dicsocket.Add(socketsend.RemoteEndPoint.ToString(),socketsend);comboBox1.Items.Add(socketsend.RemoteEndPoint.ToString());//socket.remoteendpoint可以顯示socket的ip地址和端口號//192.168.1.103:連接成功showmsg(socketsend.RemoteEndPoint.ToString() + ":" + "連接成功");//連接成功后開啟新線程接受消息Thread th = new Thread(Recive);th.IsBackground = true;th.Start(socketsend);}}catch { }}/// <summary>/// 服務器端循環接收客戶端發來的信息/// </summary>/// <param name="o"></param>void Recive(object o){while (true){try{Socket socketsend = o as Socket;byte[] b = new byte[1024 * 1024 * 2];//實際接收到的有效字節int r = socketsend.Receive(b);if (r == 0){break;}string str = Encoding.UTF8.GetString(b, 0, r);showmsg(socketsend.RemoteEndPoint.ToString() + "說:" + str);}catch {}}}/// <summary>/// 往文本框里添加文字的方法/// </summary>/// <param name="a"></param>void showmsg(string a){textBox3.AppendText(a+"\r\n"); }private void textBox1_TextChanged(object sender, EventArgs e){}private void Form1_Load(object sender, EventArgs e){Control.CheckForIllegalCrossThreadCalls = false;}/// <summary>/// 服務器給客戶端發文字消息/// </summary>/// <param name="sender"></param>/// <param name="e"></param>private void button4_Click(object sender, EventArgs e){try{List<byte> nb = new List<byte>();string str = textBox4.Text.Trim();byte[] b = System.Text.Encoding.UTF8.GetBytes(str);nb.Add(0);nb.AddRange(b);byte[] newb = nb.ToArray();string ip = comboBox1.SelectedItem.ToString();dicsocket[ip].Send(newb);//socketsend.Send(b);showmsg("我說 :" + str);}catch { }}/// <summary>/// 選擇要發送的文件/// </summary>/// <param name="sender"></param>/// <param name="e"></param>private void button2_Click(object sender, EventArgs e){OpenFileDialog ofd  = new OpenFileDialog();ofd.InitialDirectory = @"C:\Documents and Settings\Administrator\桌面";ofd.Title = "請選擇要發送的文件";ofd.Filter = "所有文件|*.*";ofd.ShowDialog(this);//加thistextBox5.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[] b = new byte[1024 * 1024 * 5];//最大5m的文件int r = fsread.Read(b, 0, b.Length);List<byte> nb = new List<byte>();nb.Add(1);//在第一位加上數字,讓客戶端可以識別服務端的指令nb.AddRange(b);//往集合中添加集合的方法。byte[] newb = nb.ToArray();dicsocket[comboBox1.SelectedItem.ToString()].Send(newb, 0, r + 1, SocketFlags.None);}}catch { }}/// <summary>/// 抖動窗口/// </summary>/// <param name="sender"></param>/// <param name="e"></param>private void button5_Click(object sender, EventArgs e)//發送消息{try{byte[] b = new byte[1];b[0] = 2;dicsocket[comboBox1.SelectedItem.ToString()].Send(b);}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 kehuduan
{public partial class Form1 : Form{public Form1(){InitializeComponent();}Socket socketsend;private void button1_Click(object sender, EventArgs e){try{socketsend = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//設置一個socketIPAddress ip = IPAddress.Parse(textBox1.Text);//將文本框中的字符串轉換成IP地址。IPEndPoint point = new IPEndPoint(ip, Convert.ToInt32(textBox2.Text));//創建IPEndpoint對象實例。包含ip地址和端口號socketsend.Connect(point);//連接到IPendpoint所在的監聽socketshowmsg("連接成功");
//開啟新線程Thread th = new Thread(Recive);th.IsBackground = true;th.Start();}catch { }}void showmsg(string str)  //在文本框中添加內容{textBox3.AppendText(str+"\r\n");}private void Form1_Load(object sender, EventArgs e){Control.CheckForIllegalCrossThreadCalls = false;//取消跨線程使用控件檢查。}void Recive()//接收{while (true){try{byte[] b = new byte[1024 * 1024 * 2];//實際接收到的有效字節int r = socketsend.Receive(b);if (r == 0){break;}if (b[0] == 0){string str = Encoding.UTF8.GetString(b, 1, r-1);  //從第二個開始截取,因為第一個元素用來判斷服務端發過來的指令。showmsg(socketsend.RemoteEndPoint.ToString() + "說:" + str);}else if (b[0] == 1){SaveFileDialog sfd = new SaveFileDialog();//保存文件對話框sfd.InitialDirectory = @"C:\Documents and Settings\Administrator\桌面";sfd.Title = "對方發送了一個文件,請選擇保存的位置";sfd.ShowDialog();string path = sfd.FileName;using (FileStream fswrite = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite))//數據流控制,用來保存文件。
                        {fswrite.Write(b,1,r-1);MessageBox.Show("保存成功");}}else if (b[0] == 2)//如果發來的字節包首個元素的值==2,就振動{ZD();}}catch{}}}private void button2_Click(object sender, EventArgs e)//發送消息{try{string str = textBox4.Text.Trim();//存下文本框中的內容byte[] b = System.Text.Encoding.UTF8.GetBytes(str);//將內容轉換成二進制流(utf8編碼)socketsend.Send(b);//發送給服務端showmsg("我說 :" + str);//將我說的話放到文本框中}catch { }}/// <summary>/// 震動窗體/// </summary>void ZD()//連續修改窗口的Location,模擬抖動窗口效果{for (int i = 0; i < 50; i++){Point a = this.Location;a.X += 5;a.Y += 5;this.Location = a;Thread.Sleep(2);a.X -=5;a.Y -=5;this.Location = a;}}}
}

知識點

//跨線程使用控件應在窗口加載時取消檢查。

//跨線程方法傳值只能傳Object類型的值,可以在方法中強制轉換成需要的類型,如 socketwatch = Object AS socket(將AS前的對象轉換成后邊的對象,如果成功返回轉換成功后的對象,否則返回null)

//鍵值集合

  Dictionary<鍵,值> 集合名 = new Dictionary<鍵, 值>();
集合名.add(鍵,值)//往集合里添加
使用 集合名[鍵] 可以訪問鍵對應的值。


posted on 2015-07-28 18:00?歐歐吉 閱讀(...) 評論(...) 編輯 收藏

轉載于:https://www.cnblogs.com/oogcn/p/4683674.html

總結

以上是生活随笔為你收集整理的C#_Socket网络编程实现的简单局域网内即时聊天,发送文件,抖动窗口。的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。