Socket通信第二版--包含文件的发送和窗口抖动




SocketServer端:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Net;
using System.Threading;
using System.IO;


namespace SocketServer
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }


        Dictionary<string, Socket> dicCbolist = new Dictionary<string, Socket>();


        private void btnStartListen_Click(object sender, EventArgs e)
        {
            try
            {
                Socket socketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                IPAddress ip = IPAddress.Parse(this.txtIP.Text);//IPAddress.Any;//new IPAddress(Encoding.Default.GetBytes(this.txtIP.Text));
                IPEndPoint point = new IPEndPoint(ip, Convert.ToInt32(this.txtPort.Text));
                socketWatch.Bind(point);
                txtLog.AppendText("监听成功!\r\n");
                socketWatch.Listen(10);
                Thread th = new Thread(Listens);
                th.IsBackground = true;
                th.Start(socketWatch);
            }
            catch { }
        }


        void Listens(object o)
        {
            try
            {
                Socket socketWatch = o as Socket;
                //循环等待客户端链接,并新创建一个发送Socket
                while (true)
                {
                    Socket socketSend = socketWatch.Accept();
                    dicCbolist.Add(socketSend.RemoteEndPoint.ToString(), socketSend);
                    cboSelectIP.Items.Add(socketSend.RemoteEndPoint.ToString());
                    txtLog.AppendText(socketSend.RemoteEndPoint.ToString() + ":" + "链接成功!\r\n");
                    cboSelectIP.SelectedItem = socketSend.RemoteEndPoint.ToString();
                    Thread th = new Thread(Recive);
                    th.IsBackground = true;
                    th.Start(socketSend);
                }
            }
            catch { }
        }
        Socket socketSend;
        void Recive(object o)
        {
            try
            {
                socketSend = o as Socket;
                while (true)
                {
                    byte[] buffer = new byte[1024 * 1024 * 5];
                    int r = socketSend.Receive(buffer);
                    if (r == 0)
                    {
                        break;
                    }
                    string str = Encoding.Default.GetString(buffer, 0, r);
                    txtLog.AppendText(socketSend.RemoteEndPoint.ToString() + ":" + str + "\r\n");


                }
            }
            catch { }
        }


        private void Form1_Load(object sender, EventArgs e)
        {
            Control.CheckForIllegalCrossThreadCalls = false;
        }
        List<byte> listByte = new List<byte>();
        private void btnSendMsg_Click(object sender, EventArgs e)
        {
            try
            {
                byte[] buffer = Encoding.Default.GetBytes(this.txtWriteMsg.Text.Trim());
                string strIp = this.cboSelectIP.SelectedItem.ToString();
                listByte.Add(0);
                listByte.AddRange(buffer);
                byte[] newBuffer = listByte.ToArray();
                dicCbolist[strIp].Send(newBuffer);
            }
            catch { }
        }


        private void btnChoose_Click(object sender, EventArgs e)
        {
            try
            {
                OpenFileDialog of = new OpenFileDialog();
                of.Title = "选择要打开的文件";
                of.Filter = "文本文件|*.txt|所有文件|*.*";
                of.ShowDialog();


                txtFilePath.Text = of.FileName.ToString();
            }
            catch { }
        }


        private void btnSendFile_Click(object sender, EventArgs e)
        {
            try
            {
                using (FileStream fs = new FileStream(txtFilePath.Text.ToString(), FileMode.OpenOrCreate, FileAccess.Read))
                {
                    byte[] buffer = new byte[1024 * 1024 * 5];
                    int r = fs.Read(buffer, 0, buffer.Length);
                    listByte.Add(1);
                    listByte.AddRange(buffer);
                    byte[] newBuffer = listByte.ToArray();


                    dicCbolist[this.cboSelectIP.SelectedItem.ToString()].Send(newBuffer, 0, r, SocketFlags.None);
                }
            }
            catch { }
        }


        private void btnShake_Click(object sender, EventArgs e)
        {
            try
            {
                byte[] buffer = new byte[1];
                buffer[0] = 2;
                dicCbolist[cboSelectIP.SelectedItem.ToString()].Send(buffer);
            }
            catch { }
        }
    }
}




SocketClient端:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Net;
using System.Threading;
using System.IO;


namespace SocketClient
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }


        Socket socketSend;


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


        private void btnConnet_Click(object sender, EventArgs e)
        {
            try
            {
                socketSend = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                IPAddress ip = IPAddress.Parse(this.txtIP.Text); //IPAddress.Any;//new IPAddress(Encoding.Default.GetBytes(this.txtIP.Text));
                IPEndPoint point = new IPEndPoint(ip, Convert.ToInt32(this.txtPort.Text));
                socketSend.Connect(point);
                txtLog.AppendText("链接成功!\r\n");


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


        }


        void Recive()
        {
            try
            {
                while (true)
                {
                    byte[] buffer = new byte[1024 * 1024 * 5];
                    int r = socketSend.Receive(buffer);
                    int i = buffer[0];
                    if (i == 0)
                    {
                        string str = Encoding.Default.GetString(buffer, 1, r);
                        this.txtLog.AppendText(socketSend.RemoteEndPoint.ToString() + ":" + str + "\r\n");
                    }
                    else if (i == 1)
                    {
                        SaveFileDialog sfd = new SaveFileDialog();
                        sfd.Title = "保存文件";
                        sfd.InitialDirectory = @"C:\Users\Administrator\Desktop";
                        sfd.ShowDialog(this);
                        string filePath = sfd.FileName;
                        using (FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Write))
                        {
                            fs.Write(buffer, 1, r);
                        }
                        MessageBox.Show("保存成功!");
                    }
                    else if (i == 2)
                    {
                        for (int point = 0; point < 100; point++)
                        {
                            this.Location = new Point(this.ClientRectangle.Width, this.ClientRectangle.Width);
                            this.Location = new Point(this.ClientRectangle.Height + 20, this.ClientRectangle.Width + 50);
                        }
                    }
                }
            }
            catch { }
        }


        private void btnSendMsg_Click(object sender, EventArgs e)
        {
            try
            {
                byte[] buffer = Encoding.Default.GetBytes(this.txtWriteMsg.Text.Trim());
                socketSend.Send(buffer);
            }
            catch { }
        }
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值