基于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 _01serverFrm
{
    public partial class serverFrm : Form
    {
        public serverFrm()
        {
            InitializeComponent();
        }
        /// <summary>
        /// 1.服务端的socket绑定ip和端口号,设置监听队列listen后开始检查是否有网络连接到服务器,用accept();
        /// 2.服务端用receive接收客服端发来的字节数组
        /// 3.客户端通过connect连接到服务器后通过send发送字节数组到服务端
        /// 4.服务器通过send()发送到客户端,客户端通过receive接收
        /// 5.服务器通过设置下拉框给指定的客服端发送数据,用字典存储ip接口和socket的映射关系
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnListen_Click(object sender, EventArgs e)
        {
            Socket socketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPAddress ip = IPAddress.Any;
            IPEndPoint point = new IPEndPoint(ip,Convert.ToInt32(txtPort.Text));
            socketWatch.Bind(point);
            socketWatch.Listen(10);
            ShowMsg("监听成功!");

            Thread th = new Thread(Listen);
            th.IsBackground=true;
            th.Start(socketWatch);
        }
        //Socket socketSend;
        Dictionary<string,Socket> dicSocket = new Dictionary<string,Socket>();
        void Listen(object o)
        {
            Socket socketWatch = o as Socket;
            while (true)
            {
                Socket socketSend = socketWatch.Accept();
                dicSocket.Add(socketSend.RemoteEndPoint.ToString(), socketSend);
                cboAddress.Items.Add(socketSend.RemoteEndPoint.ToString());
                cboAddress.SelectedIndex = 0;//设置该下拉框默认选中第一项。
                ShowMsg(socketSend.RemoteEndPoint.ToString() + ":" + "连接成功");
                Thread th = new Thread(Receive);
                th.IsBackground = true;
                th.Start(socketSend); 
            }
        }
        void Receive(object o)
        {
            Socket socketSend = o as Socket;
            while (true)
            {
                byte[] buffer = new byte[1024];
                int r = socketSend.Receive(buffer);
                if (r == 0)
                {
                    break;
                }
                string str = Encoding.UTF8.GetString(buffer, 0, r);
                ShowMsg(socketSend.RemoteEndPoint.ToString() + ":" + str);
            }
        }
        void ShowMsg(string str)
        {
            txtLog.AppendText(str + "\r\n");
        }

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

        private void btnSend_Click(object sender, EventArgs e)
        {
            //byte[] buffer = new byte[1024]; 给数组宽度在下面添加到列表的时候按实际宽度来的,不合理,
            byte[] buffer = Encoding.UTF8.GetBytes(txtConversation.Text);
            List<byte> list = new List<byte>();
            list.Add(0);
            list.AddRange(buffer);
            byte[] newBuffer = list.ToArray();
            dicSocket[cboAddress.SelectedItem.ToString()].Send(newBuffer);//这里的key不能加双引号,报错了好多次了
            txtConversation.Text = "";
        }

        private void btnChoose_Click(object sender, EventArgs e)
        {
            using (OpenFileDialog ofd = new OpenFileDialog() )
            {
                ofd.Title = "请选择文件";
                ofd.ShowDialog();
                txtFile.Text = ofd.FileName;
            }
        }
        //List<byte> list = new List<byte>();
        private void btnSendFile_Click(object sender, EventArgs e)
        {
            using (FileStream fs = new FileStream(txtFile.Text,FileMode.OpenOrCreate,FileAccess.Read))
            {
                byte[] buffer = new byte[1024*1024*3];
                int r = fs.Read(buffer, 0, buffer.Length);
                List<byte> list = new List<byte>();
                list.Add(1);
                list.AddRange(buffer);
                byte[] newBuffer = list.ToArray();
                dicSocket[cboAddress.SelectedItem.ToString()].Send(newBuffer, 0, r + 1, SocketFlags.None);
            }
        }

        private void btnTremble_Click(object sender, EventArgs e)
        {
            byte[] buffer = new byte[1];
            buffer[0] = 2;
            dicSocket[cboAddress.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 _02clientFrm
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        Socket socketConnection;
        private void btnConnection_Click(object sender, EventArgs e)
        {
            socketConnection = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPAddress ip = IPAddress.Parse(txtAddress.Text); 
            IPEndPoint point = new IPEndPoint(ip, Convert.ToInt32(txtPort.Text));
            socketConnection.Connect(point);
            ShowMsg("连接成功,连接到"+socketConnection.RemoteEndPoint.ToString());

            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)
        {
            byte[] buffer = new byte[1024];
            buffer = Encoding.UTF8.GetBytes(txtConversation.Text);
            socketConnection.Send(buffer);
            txtConversation.Text = "";
        }
        void Receive()
        {
            while (true)
            {
                byte[] buffer = new byte[1024*1024*3];
                int r = socketConnection.Receive(buffer);
                if (r == 0)
                {
                    break;
                }
                switch (buffer[0])
                {
                    case 0:
                        string str = Encoding.UTF8.GetString(buffer, 1, r - 1);
                        ShowMsg(socketConnection.RemoteEndPoint.ToString() + ":" + str);
                        break;
                    case 1:
                        using (SaveFileDialog sfd = new SaveFileDialog())
                        {
                            sfd.ShowDialog(this); //客户端弹不出来,加个this
                            string strFileName = sfd.FileName;
                            using (FileStream fsWrite = new FileStream(strFileName, FileMode.OpenOrCreate, FileAccess.Write))
                            {
                                fsWrite.Write(buffer, 1, r - 1);
                            }
                            MessageBox.Show("保存成功");
                        }
                        break;
                    case 2:
                        Tremble();
                        break;

                }

            }
        }
        void Tremble()
        {
            for (int i = 0; i < 500; i++)
            {
                this.Location = new Point(0, 0);
                this.Location = new Point(20, 20); 
            }
        }

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

原文地址:http://www.cnblogs.com/wheniwasjustakid/p/16818802.html

1. 本站所有资源来源于用户上传和网络,如有侵权请邮件联系站长! 2. 分享目的仅供大家学习和交流,请务用于商业用途! 3. 如果你也有好源码或者教程,可以到用户中心发布,分享有积分奖励和额外收入! 4. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解! 5. 如有链接无法下载、失效或广告,请联系管理员处理! 6. 本站资源售价只是赞助,收取费用仅维持本站的日常运营所需! 7. 如遇到加密压缩包,默认解压密码为"gltf",如遇到无法解压的请联系管理员! 8. 因为资源和程序源码均为可复制品,所以不支持任何理由的退款兑现,请斟酌后支付下载 声明:如果标题没有注明"已测试"或者"测试可用"等字样的资源源码均未经过站长测试.特别注意没有标注的源码不保证任何可用性