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 WindowsFormsApp1
{
    public partial class MainFrm : Form
    {
        List<Socket> ClientProxSocketList = new List<Socket>();
        public MainFrm()
        {
            InitializeComponent();
        }

        private void label1_Click(object sender, EventArgs e)
        {

        }

        private void textBox3_TextChanged(object sender, EventArgs e)
        {

        }

        private void label2_Click(object sender, EventArgs e)
        {

        }

        /// <summary>
        /// 启动
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            //创建Socket
            Socket socket =new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        
            //绑定端口IP
            socket.Bind(new IPEndPoint(IPAddress.Parse(txtIP.Text),int.Parse(txtPort.Text)));

            //开启监听
            socket.Listen(10);//最大监听

            //开启客户端链接
            ThreadPool.QueueUserWorkItem(new WaitCallback(AcceptClientConnect),socket);//将socket传给AcceptClientConnect做形参


        }

        /// <summary>
        /// 接收服务连接
        /// </summary>
        /// <param name="socket"></param>
        private void AcceptClientConnect(object socket)
        {
            var serverSocket=socket as Socket;//将形参转换为Socket形式
            AppendTextToTxtLog("服务器开始接收客户端链接.");
            while (true)
            {
                var proxSocket=serverSocket.Accept();//创建Socket连接,并返回一个Socket对象
                AppendTextToTxtLog(string.Format("客户端:{0}连接上了",proxSocket.RemoteEndPoint.ToString()));
                ClientProxSocketList.Add(proxSocket);

                //不断接收客户端发来的消息
                ThreadPool.QueueUserWorkItem(ReceiveData,proxSocket);
            }

        }

        /// <summary>
        /// 接收客户端消息
        /// </summary>
        /// <param name="socket"></param>
        public void ReceiveData(object socket)
        {
            var proxSocket=socket as Socket;
            byte[] data=new byte[1024*1024];
            while (true)
            {
                int len= 0;
                try
                {
                    len = proxSocket.Receive(data, 0, data.Length, SocketFlags.None);//从proxSocket的Socket接收数据,并将其存储在名为data的字节数组中,然后使用接收到的字节数更新len变量
                }
                catch (Exception ex)
                {
                    //异常退出
                    AppendTextToTxtLog(string.Format("客户端{0}:非正常退出", proxSocket.RemoteEndPoint.ToString()));
                    ClientProxSocketList.Remove(proxSocket);
                    return;
                }
                
                
                if (len <= 0)
                {
                    //客户端正常退出
                    AppendTextToTxtLog(string.Format("客户端{0}:正常退出", proxSocket.RemoteEndPoint.ToString()));
                    ClientProxSocketList.Remove(proxSocket);
                    return;
                }
                
                //把接收的数据放文本框上面
                string str=Encoding.Default.GetString(data,0,len);
                AppendTextToTxtLog(string.Format("接收客户端:{0}的消息是:{1}",proxSocket.RemoteEndPoint.ToString(),str));
            }
        }

        /// <summary>
        /// 往日志的文本框上追加数据
        /// </summary>
        /// <param name="txt"></param>
        public void AppendTextToTxtLog(string txt)
        {          
            if (txtLog.InvokeRequired)//判断是否跨线程
            {
                txtLog.Invoke(new Action<string>
                    (s => { this.txtLog.Text = string.Format("{0}\r\n{1}", s, txtLog.Text); })
                    , txt);
            }
            else
            {
                this.txtLog.Text = string.Format(txt);
            }
        }



        /// <summary>
        /// 发送消息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSendMsg_Click(object sender, EventArgs e)
        {
            foreach (var proxSocket in ClientProxSocketList)
            {
                if (proxSocket.Connected)
                {
                    byte[] data=Encoding.Default.GetBytes(txtMsg.Text);
                    proxSocket.Send(data, 0, data.Length, SocketFlags.None);
                }
            }
        }

        private void txtIP_TextChanged(object sender, EventArgs e)
        {

        }

        private void MainFrm_Load(object sender, EventArgs e)
        {

        }

        private void btnSendShake_Click(object sender, EventArgs e)
        {
            foreach (var proxSocket in ClientProxSocketList)
            {
                if (proxSocket.Connected)
                {
                  proxSocket.Send(new byte[] {2},SocketFlags.None);
                }
            }
        }

        /// <summary>
        /// 发送文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSendFile_Click(object sender, EventArgs e)
        {
            using (OpenFileDialog ofd = new OpenFileDialog())//释放文件
            {
                 if (ofd.ShowDialog() != DialogResult.OK)// 如果没有显示文件选择对话框
                 {
                       return;
                 }
                byte[] data=File.ReadAllBytes(ofd.FileName);
                byte[] result=new byte[data.Length+1];
                result[0] = 3;
                Buffer.BlockCopy(data,0,result,1,data.Length);


                foreach (var proxSocket in ClientProxSocketList)
                {
                    if (!proxSocket.Connected)
                    {
                        continue;
                    }
                    proxSocket.Send(result, SocketFlags.None);
                }
            }

        }
    }
}
C#中,Socket服务端是通过System.Net套接字类来创建网络通信的基础。Socket代表了一个网络连接点,它允许程序发送和接收数据。以下是建立一个基本的TCP Socket服务器的基本步骤: 1. **创建Socket实例**: 使用`Socket`类的构造函数创建一个新的TCP套接字,例如`TcpListener serverSocket = new TcpListener(IPAddress.Any, port)`,这里`IPAddress.Any`表示监听所有可用的IP地址,`port`是你想要使用的端口号。 2. **开始监听**: 调用`StartListening()`方法开启监听,服务器会等待客户端的连接请求。 3. **接受连接**: 使用`AcceptSocket()`方法接收一个新的连接请求,这将返回一个新的`Socket`实例,用于与客户端通信。 4. **处理连接**: 循环读取并处理客户端发送的消息,可以使用`Receive`方法接收数据,并根据需要编写相应的响应。 5. **关闭连接**: 当完成通信后,记得关闭连接,即`client.Close()`。 下面是一个简单的示例代码片段: ```csharp using System; using System.Net; using System.Net.Sockets; class Program { static void Main() { TcpListener listener = new TcpListener(IPAddress.Any, 12345); listener.Start(); Console.WriteLine("Server is listening on port {0}", listener.LocalEndPoint.Port); while (true) { Socket client = listener.AcceptSocket(); Console.WriteLine("Accepted connection from " + client.RemoteEndPoint.ToString()); // Handle the client connection here... byte[] buffer = new byte[256]; int bytesRead = client.Receive(buffer); string message = System.Text.Encoding.ASCII.GetString(buffer, 0, bytesRead); Console.WriteLine("Received: " + message); // Send a response back to the client... byte[] response = Encoding.ASCII.GetBytes("Hello, Client!"); client.Send(response, 0, response.Length); client.Close(); // Close the connection after handling it } } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值