CSharp中Socket网络编程(四)全部代码附UI图

第一部分:整个通信过程梳理;文末附全套代码;


第二部分:重要bug完善


第三部分:消息类型编码:自定义通信协议


本篇为第四部分:全套代码


服务器端:

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 server
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        Socket socketWatch;
        Dictionary<string, Socket> dicSocket = new Dictionary<string, Socket>();

        private void btnStart_Click(object sender, EventArgs e)
        {
            socketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPAddress ip = IPAddress.Any;
            IPEndPoint port =new IPEndPoint(ip, Convert.ToInt32(txtPort.Text));
            socketWatch.Bind(port);
            socketWatch.Listen(10);
            ShowMsg("开始监听");

            Thread th = new Thread(Listen);
            th.IsBackground = true;
            th.Start(socketWatch);
        }

        void ShowMsg(string str)
        {
            txtLog.AppendText(str + "\r\n");
        }

        Socket socketSend;

        void Listen(object o)
        {
            socketWatch = o as Socket;
            try
            {
                while (true)
                {
                    socketSend = socketWatch.Accept();
                    ShowMsg(socketSend.RemoteEndPoint.ToString() + ":" + "进入成功");
                    dicSocket.Add(socketSend.RemoteEndPoint.ToString(), socketSend);
                    cboUsers.Items.Add(socketSend.RemoteEndPoint.ToString());

                    Thread th = new Thread(Receive);
                    th.IsBackground = true;
                    th.Start();
                }
            }
            catch
            { }
        }

        void Receive()
        {
            try
            {
                while (true)
                {
                    byte[] buffer = new byte[1024 * 1024 * 10];
                    int r = socketSend.Receive(buffer);
                    if (r == 0)
                    {
                        break;
                    }
                    string str = Encoding.UTF8.GetString(buffer, 0, r);
                    ShowMsg(socketSend.RemoteEndPoint.ToString() + ":" + str);
                }
            }
            catch
            { }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            Control.CheckForIllegalCrossThreadCalls = false;
        }

        private void btnSend_Click(object sender, EventArgs e)
        {
            string str = txtMsg.Text;
            byte[] buffer = Encoding.UTF8.GetBytes(str);
            List<byte> list = new List<byte>();
            list.Add(0);
            list.AddRange(buffer);
            // 将泛型集合转化为数组。
            byte[] newBuffer = list.ToArray();
            //buffer = list.ToArray();   // 因为类型长度不同,无法赋值。所以新建。
            // dicSocket[cboUsers.SelectedItem.ToString()].Send(buffer);
            dicSocket[cboUsers.SelectedItem.ToString()].Send(newBuffer);
        }

        /// <summary>
        /// 选择要发送的文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSelect_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.InitialDirectory = @"C:\Users\futurecloud\Desktop";
            ofd.Title="请选择你要传输的文件";
            ofd.Filter = "所有文件|*.*";
            ofd.ShowDialog();
            //this.txtPath.Text = ofd.SafeFileName;
            txtPath.Text = ofd.FileName;
        }

        private void btnSendFile_Click(object sender, EventArgs e)
        {
            string path = txtPath.Text;
            using (FileStream fsRead=new FileStream(path, FileMode.Open, FileAccess.Read))
            {
                byte[] buffer = new byte[1024 * 1024 * 10];
                int r = fsRead.Read(buffer, 0, buffer.Length);
                List<byte> list = new List<byte>();
                list.Add(1);
                list.AddRange(buffer);

                byte[] newBuffer = list.ToArray();
                // send有很多重载:有限制大小的。
                dicSocket[cboUsers.SelectedItem.ToString()].Send(newBuffer, 0, r+1, SocketFlags.None);
            }
        }

        private void btnZD_Click(object sender, EventArgs e)
        {
            byte[] buffer = new byte[1];
            buffer[0] = 2;
            dicSocket[cboUsers.SelectedItem.ToString()].Send(buffer);
        }
    }
}

客户端

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 Client
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        Socket socketSend;

        private void btnStart_Click(object sender, EventArgs e)
        {
            socketSend = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPAddress ip = IPAddress.Parse(txtServer.Text);
            IPEndPoint port = new IPEndPoint(ip, Convert.ToInt32(txtPort.Text));
            socketSend.Connect(port);
            ShowMsg("连通服务器");

            Thread th = new Thread(Receive);
            th.IsBackground = true;
            th.Start();
        }

        void ShowMsg(string str)
        {
            txtLog.AppendText(str + "\r\n");
        }

        private void btnSend_Click(object sender, EventArgs e)
        {
            string str = txtMsg.Text;
            byte[] buffer = System.Text.Encoding.UTF8.GetBytes(str);
            socketSend.Send(buffer);
        }

        void Receive()
        {
            try
            {
                while (true)
                {
                    byte[] buffer = new byte[1024 * 1024 * 10];
                    int r = socketSend.Receive(buffer);
                    if (r == 0)
                    {
                        break;
                    }
                    if (buffer[0]==0)
                    {
                        string str = Encoding.UTF8.GetString(buffer, 1, r-1);
                        ShowMsg(socketSend.RemoteEndPoint.ToString() + ":" + str);
                    }
                    else if (buffer[0]==1)
                    {
                        SaveFileDialog sfd = new SaveFileDialog();
                        sfd.InitialDirectory = @"C:\Users\futurecloud\Desktop";
                        sfd.Title = "请选择你要保存的文件路径:";
                        sfd.Filter = "所有文件|*.*";
                        sfd.ShowDialog(this);   // 不加这个this这个框不弹出来。
                        // 写入文件:
                        string path = sfd.FileName;
                        using (FileStream fsWrite = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write))
                        {
                            fsWrite.Write(buffer,1,r-1);
                        }
                        //ShowMsg("写入文件成功。");
                        MessageBox.Show("文件写入成功");
                    }
                    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(210, 210);

                this.Location = new Point(this.Location.X, this.Location.Y);
                this.Location = new Point(this.Location.X+10, this.Location.Y+10);
                this.Location = new Point(this.Location.X-10, this.Location.Y-10);
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            Control.CheckForIllegalCrossThreadCalls = false;
        }
    }
}

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值