1. 程式人生 > 實用技巧 >C# Winform TCP發訊息

C# Winform TCP發訊息

服務端:

程式碼:

using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace SocketStudy
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        /// <summary>
        /// 負責通訊的socket
        /// </summary>
        Socket socketSend;

        /// <summary>
        /// 負責監聽Socket
        /// </summary>
        Socket socket;

        /// <summary>
        /// 存放連線的socket
        /// </summary>
        Dictionary<string, Socket> dictionary = new Dictionary<string, Socket>();

        /// <summary>
        /// 開始監聽
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            //建立監聽的socket,
            //SocketType.Stream 流式對應tcp協議
            //Dgram,資料報對應UDP協議
            socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            //建立IP地址和埠號
            IPAddress ip = IPAddress.Any;//IPAddress.Parse(textServerIP.Text);
            int port = Convert.ToInt32(textServerPort.Text);
            IPEndPoint iPEndPoint = new IPEndPoint(ip, port);

            //讓負責監聽的Socket繫結ip和埠號
            socket.Bind(iPEndPoint);

            ShowLog("監聽成功!" + ip + "\t" + port);//列印日誌

            //設定監聽佇列
            socket.Listen(10);//一段時間內可以連線到的伺服器的最大數量
            Thread thread = new Thread(Listen);
            thread.IsBackground = true;
            thread.Start(socket);
        }

        /// <summary>
        /// 使用執行緒來接收資料
        /// </summary>
        /// <param name="o"></param>
        private void Listen(object o)
        {
            Socket socket = o as Socket;
            while(true){
                //負責監聽的socket是用來接收客戶端連線
                //建立負責通訊的socket
                socketSend = socket.Accept();
                dictionary.Add(socketSend.RemoteEndPoint.ToString(), socketSend);
                clientCombo.Items.Add(socketSend.RemoteEndPoint.ToString());

                ShowLog(socketSend.RemoteEndPoint.ToString() + "已連線");

                //開啟新執行緒,接收客戶端發來的資訊
                Thread th = new Thread(receive);
                th.IsBackground = true;
                th.Start(socketSend);
            }
        }

        //伺服器接收客戶端傳來的訊息
        private void receive(object o)
        {
            Socket socketSend = o as Socket;
            while (true)
            {
                try
                {
                    //客戶端連線成功後,伺服器接收客戶端發來的訊息
                    byte[] buffer = new byte[1024 * 1024 * 2];//2M大小
                                                              //接收到的有效位元組數
                    int length = socketSend.Receive(buffer);
                    if (length == 0)
                    {
                        ShowLog(socketSend.RemoteEndPoint.ToString() + "下線了。");
                        dictionary[socketSend.RemoteEndPoint.ToString()].Shutdown(SocketShutdown.Both);
                        dictionary[socketSend.RemoteEndPoint.ToString()].Disconnect(false);
                        dictionary[socketSend.RemoteEndPoint.ToString()].Close();
                        break;
                    }
                    string str = Encoding.ASCII.GetString(buffer, 0, length);
                    ShowLog(socketSend.RemoteEndPoint.ToString() + "\n\t" + str);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }
        }

        /// <summary>
        /// 日誌列印
        /// </summary>
        /// <param name="str"></param>
        private void ShowLog(string str)
        {
            textLog.AppendText(str + "\r\n");
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //取消對跨執行緒呼叫而產生的錯誤
            Control.CheckForIllegalCrossThreadCalls = false;
        }

        private void sendMsgBtn_Click(object sender, EventArgs e)
        {
            string txt = textMsg.Text;
            byte[] buffer = Encoding.UTF8.GetBytes(txt);
            List<byte> list = new List<byte>();
            list.Add(0); // 0 為 發訊息
            list.AddRange(buffer);
            byte[] newBuffer = list.ToArray();
            //socketSend.Send(buffer);
            string ip = clientCombo.SelectedItem.ToString();//獲取選中的ip地址
            Socket socketsend=dictionary[ip];
            socketsend.Send(newBuffer);
        }

        private void selectBtn_Click(object sender, EventArgs e)
        {
            OpenFileDialog fileDialog = new OpenFileDialog();
            fileDialog.InitialDirectory=@"D:";
            fileDialog.Title="選擇檔案";
            fileDialog.Filter = "所有檔案|*.*";
            fileDialog.ShowDialog();

            pathTxt.Text = fileDialog.FileName;

        }

        /// <summary>
        /// 發文件,
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void sendFileBtn_Click(object sender, EventArgs e)
        {
            string path = pathTxt.Text;
            FileStream fileStream = new FileStream(path,FileMode.Open,FileAccess.Read);

            byte[] buffer = new byte[1024*1024*3];
            buffer[0] = 1;// 1 為發文件的標誌位
            int length = fileStream.Read(buffer, 1, buffer.Length-1);
            fileStream.Close();
            string ip = clientCombo.SelectedItem.ToString();//獲取選中的ip地址
            Socket socketsend = dictionary[ip];
            socketsend.Send(buffer,0, length+1, SocketFlags.None);
        }

        /// <summary>
        /// 抖一抖
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void shockBtn_Click(object sender, EventArgs e)
        {
            byte[] buffer = new byte[1];
            buffer[0] = 2;// 2 為抖一抖
            string ip = clientCombo.SelectedItem.ToString();//獲取選中的ip地址
            Socket socketsend = dictionary[ip];
            socketsend.Send(buffer);
        }

        /// <summary>
        /// 關閉前關閉socket
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            try
            {
                socket.Shutdown(SocketShutdown.Both);
                socket.Disconnect(false);
                socket.Close();
            }
            catch
            {
                socket.Close();
            }
        }
    }
}

  

客戶端:

程式碼:using System;

using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace Client
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        Socket socket;
      //連線 private void connectBtn_Click(object sender, EventArgs e) { try { //建立負責通訊的socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //地址、埠 IPAddress ip = IPAddress.Parse(ipText.Text); int serverPort = Convert.ToInt32(portText.Text); IPEndPoint port = new IPEndPoint(ip, serverPort); //連線到伺服器 socket.Connect(port); ShowLog("已連線"); //啟動接收資料執行緒 Thread th = new Thread(receive); th.IsBackground = true; th.Start(); } catch { } }
    //日誌 private void ShowLog(string str) { textLog.AppendText(str + "\r\n"); } /// <summary> /// 發訊息 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void sendMsgBtn_Click(object sender, EventArgs e) { try { string txt = sendMsg.Text; byte[] buffer = Encoding.ASCII.GetBytes(txt);//ascii編碼 socket.Send(buffer); } catch { } }     
    //接收訊息
private void receive() { while (true) { try { byte[] buffer = new byte[1024 * 1024 * 2]; int length = socket.Receive(buffer); if (length == 0) { break; } if (buffer[0] == 0) { string txt = Encoding.UTF8.GetString(buffer, 1, length-1); ShowLog(socket.RemoteEndPoint + ":\r\t" + txt); }else if (buffer[0] == 1) { SaveFileDialog saveFileDialog = new SaveFileDialog(); saveFileDialog.InitialDirectory = @"E:\"; saveFileDialog.Title = "餓了吃什麼"; saveFileDialog.Filter = "所有檔案 | *.*"; saveFileDialog.ShowDialog(this); string path = saveFileDialog.FileName; FileStream fileStreamWrite = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write); fileStreamWrite.Write(buffer,1,length-1); fileStreamWrite.Close(); MessageBox.Show("儲存成功"); }else if (buffer[0] == 2) { ZD(); } } catch { } } }       //震動 private void ZD() { for(int i=0;i<20;i++){ if (i%2==0) { this.Location = new System.Drawing.Point(500, 500); } else { this.Location = new System.Drawing.Point(530, 530); } Thread.Sleep(20); } }     //取消跨執行緒檢查 private void Form1_Load(object sender, EventArgs e) { Control.CheckForIllegalCrossThreadCalls = false; }     //關閉前關掉socket private void Form1_FormClosing(object sender, FormClosingEventArgs e) { socket.Disconnect(false); socket.Close(); }       //斷開連線 private void button1_Click(object sender, EventArgs e) { if (socket !=null) { socket.Disconnect(false); } } } }

  

結果:

注:

  這部分是本人根據bilibili中一個up學的,程式碼和他的幾乎不差,現在找不到up了,侵刪