Socket通信客户端和服务端代码

这两天研究了下Socket通信,简单实现的客户端和服务端代码

先上winfrom图片,客户端和服务端一样

 

服务端代码:

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

namespace Server
{
    public partial class Form1 : Form
    {
        private List<Socket> listSocket = new List<Socket>();
        public Form1()
        {
            InitializeComponent();
            Control.CheckForIllegalCrossThreadCalls = false;
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            /*
             * AddressFamily.InterNetwork:寻址方式
             * SocketType.Stream:传输数据方式
             * ProtocolType.Tcp:通信协议
             */
            //1.创建一个socket对象
            Socket socket = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);

            //2.创建一个IP地址
            IPAddress address =IPAddress.Parse(txtIP.Text.Trim());

            //3.创建一个EndPoint
            IPEndPoint ipEndPoint = new IPEndPoint(address,int.Parse(txtPort.Text));

            //4.绑定一个端口:独享此端口
            socket.Bind(ipEndPoint);

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

            AddShow("服务器启动,开始监听。。。");
            //6.开始接受客户端的连接
            //此代码一执行就阻塞当前线程,等待客户端的连接
            Task task = Task.Factory.StartNew(x => {
                Socket serverSocket = x as Socket;
                while (true)
                {
                    //客户端一连接上之后,服务器端自动生产一个跟客户端通信的socket
                    Socket workSocket = serverSocket.Accept();
                    AddShow("有一个连接上"+workSocket.RemoteEndPoint.ToString());
                    workSocket.Send(Encoding.Default.GetBytes("你好"));

                    listSocket.Add(workSocket);

                    //接收消息
                    Task t = Task.Factory.StartNew(c => {
                        Socket recSocket = c as Socket;
                        while (true)
                        {
                            try
                            {
                                byte[] bufferData = new byte[1024 * 1024];
                                int length = recSocket.Receive(bufferData);
                                if (length <= 0)
                                {
                                    AddShow(recSocket.RemoteEndPoint.ToString() + "正常退出");
                                    listSocket.Remove(recSocket);
                                    //客户端退出会发送一个空字节过来
                                    recSocket.Shutdown(SocketShutdown.Both);
                                    recSocket.Close();
                                    
                                    return;
                                }
                                string recStr = Encoding.Default.GetString(bufferData, 0, length);
                                AddShow(recSocket.RemoteEndPoint.ToString());
                                AddShow(recStr);
                            }
                            catch (Exception ex)
                            {
                                //异常退出捕获
                                AddShow(recSocket.RemoteEndPoint.ToString() + "异常退出");
                                listSocket.Remove(recSocket);
                                //客户端退出会发送一个空字节过来
                                recSocket.Shutdown(SocketShutdown.Both);
                                recSocket.Close();
                                
                            }
                        }
                    },workSocket);
                }
               
            },socket);
            
        }

        public void AddShow(string message)
        {
            //判断现在线程是否是创建txtShow的线程
            if (txtShow.InvokeRequired)
            {
                //在拥有该线程的句柄上去执行
                txtShow.Invoke(() =>
                {
                    this.txtShow.Text += message + "\r\n";
                });
            }
            else
            {
                this.txtShow.Text += message + "\r\n";
            }
        }

        private void btnSend_Click(object sender, EventArgs e)
        {
            string str = txtMsg.Text.Trim();
            byte[] data = Encoding.Default.GetBytes(str);
            //群发消息
            foreach (Socket item in listSocket)
            {
                item.Send(data);
            }
        }
    }
}
View Code

客户端代码:

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

namespace Client
{
    public partial class Form1 : Form
    {
        Socket connectSocket = null;
        public Form1()
        {
            InitializeComponent();
            Control.CheckForIllegalCrossThreadCalls = false;
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            //1.创建一个socket连接
            Socket socket = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);

            //2.连接到客户端
            socket.Connect(IPAddress.Parse(txtIP.Text.Trim()),int.Parse(txtPort.Text.Trim()));

            AddShow(socket.RemoteEndPoint.ToString()+"连接成功");
            connectSocket = socket;

            //3.开启异步线程,不停接收消息
            Task task = Task.Factory.StartNew(()=> {
                while (true)
                {
                    try
                    {
                        byte[] bufferData = new byte[1024 * 1024];
                        int length = connectSocket.Receive(bufferData);
                        if (length<=0)
                        {
                            //服务器退出,发送空消息
                            AddShow("连接正常退出");
                            connectSocket.Shutdown(SocketShutdown.Both);
                            connectSocket.Close();
                            return;
                        }
                        string str = Encoding.Default.GetString(bufferData, 0, length);
                        AddShow(connectSocket.RemoteEndPoint.ToString());
                        AddShow(str);
                    }
                    catch (Exception ex)
                    {
                        AddShow("连接异常退出");
                        if (connectSocket!=null&&connectSocket.Connected)
                        {
                            connectSocket.Shutdown(SocketShutdown.Both);
                            connectSocket.Close();
                        }
                        return;
                    }
                }
               
            });
        }

        public void AddShow(string message)
        {
            if (txtShow.InvokeRequired)
            {
                txtShow.Invoke(() => {
                    this.txtShow.Text += message + "\r\n";
                });
            }
            else
            {
                this.txtShow.Text += message + "\r\n";
            }
            
        }

        private void btnSend_Click(object sender, EventArgs e)
        {
            byte[] data = Encoding.Default.GetBytes(txtMsg.Text.Trim());
            connectSocket.Send(data);
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            //关闭窗体同时关闭socket
            if (connectSocket!=null&&connectSocket.Connected)
            {
                connectSocket.Shutdown(SocketShutdown.Both);
                connectSocket.Close();
            }
        }
    }
}
View Code

 

转载于:https://www.cnblogs.com/zhuyapeng/p/6680539.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值