初步认识Socket网络编程

Socket通信基本流程图

 

服务端代码编写

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
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 Form14 : Form
    {
        public Form14()
        {
            InitializeComponent();
        }

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

        private void BtnListen_Click(object sender, EventArgs e)
        {
            try
            {
                //当点击开始监听时,在服务器创建一个负责监听IP地址跟端口号的Socket
                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);
                showMsg("监听成功");
                //设置监听队列
                socketWatch.Listen(10);
                Thread th = new Thread(Listen);
                th.IsBackground = true;
                th.Start(socketWatch);
            }
            catch (Exception)
            {

            }


        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="o">被线程执行的函数,如果有参数,必须是object类型</param>
        void Listen(object o)
        {
            Socket socketWatch = o as Socket;

            while (true)
            {
                try//凡是涉及到网络编程的,可能会出现各种各样的异常,为了避免给用户看到,使用异常捕获
                {
                    //等待客户端的连接 并且创建一个负责通信的Socket
                    Socket socketSend = socketWatch.Accept();
                    showMsg(socketSend.RemoteEndPoint.ToString() + ":" + "连接成功");
                    //开启 一个新线程不停的接收客户端发送过来的消息
                    Thread th = new Thread(Recive);
                    th.IsBackground = true;
                    th.Start(socketSend);
                }
                catch (Exception)
                {
                }


            }

        }
        /// <summary>
        /// 服务器端不停的接收客户端发送过来的消息
        /// </summary>
        /// <param name="o"></param>
        /// 
        Socket socketSend;
        void Recive(object o)
        {
            socketSend = o as Socket;
            while (true)
            {

                try//凡是涉及到网络编程的,可能会出现各种各样的异常,为了避免给用户看到,使用异常捕获
                {
                    //客户端连接成功后,服务器应该接收客户端发过来的消息
                    byte[] buffer = new byte[1024 * 1024 * 2];
                    //实际接收到的有效字节数
                    int r = socketSend.Receive(buffer);
                    if (r == 0)//当用户退出实际接收到的字节数为0,就应该让跳出循环,结束接收客户端发过来的消息。
                    {
                        break;
                    }
                    string str = Encoding.UTF8.GetString(buffer, 0, r);
                    showMsg(socketSend.RemoteEndPoint + ":" + str);
                }
                catch (Exception)
                {
                }


            }
        }

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

        private void textBox1_TextChanged(object sender, EventArgs e)
        {

        }
        /// <summary>
        /// 服务器给客户端发送消息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSend_Click(object sender, EventArgs e)
        {
            string str = txtMsg.Text;
            byte[] buffer = System.Text.Encoding.UTF8.GetBytes(str);
            socketSend.Send(buffer);

        }
    }
}

客户端代码编写

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
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 Form15 : Form
    {
        public Form15()
        {
            InitializeComponent();
        }
        Socket socketSend;
        private void btnStart_Click(object sender, EventArgs e)
        {
            //创建负责通信的Socket
             socketSend = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
            IPAddress ip = IPAddress.Parse(txtServer.Text);
            IPEndPoint point = new IPEndPoint(ip,Convert.ToInt32(txtPort.Text));
            //获得要连接的远程服务器应用程序的IP地址和端口号
            socketSend.Connect(point);
            ShowMsg("连接成功");

            //开启一个线程不停的接收服务端发来的消息
            Thread th = new Thread(Recive);
            th.IsBackground= true;
            th.Start();


        }

        /// <summary>
        /// 不停的接收服务器发来的消息
        /// </summary>
        void Recive() {
            while (true)
            {
                byte[] buffer = new byte[1024 * 1024 * 3];
                //实际接收到的有效字节数
                int r = socketSend.Receive(buffer);
                if (r == 0) {
                    break;
                }   
                string s = Encoding.UTF8.GetString(buffer,0,r);
                ShowMsg(socketSend.RemoteEndPoint+":"+s);

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

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

            socketSend.Send(buffer);
        }

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值